gpt4 book ai didi

c++ - C 如何处理 char 和?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:06:46 24 4
gpt4 key购买 nike

当我在 C++ 中调用重载函数 foo 时,如下所示:

foo('e' - (char) 5)

它可以根据类型结果输出“this is a char”或“this is an int”。我从我的程序中得到“这是一个整数”,就像这样:

#include <iostream>

void foo(char x)
{
std::cout << "output is a char" << std::endl;
}
void foo(int x)
{
std::cout << "output is an int" << std::endl;
}
int main()
{
foo('a' + (char) 5);
}

我的导师说,在 C 中,上面的表达式 ('a' + (char) 5) 的计算结果为 char。我在 C99 标准中看到 chars 被提升为 ints 以求和,但是 C 是否在完成后将它们重新转换为 chars?我找不到任何看起来可信的引用资料,以某种方式说明 C 在完成提升并找到总和后实际做了什么。

总和是作为 int 还是作为 char 给出的?我如何在 C 中证明这一点,或者是否有我不理解/找不到的引用?

最佳答案

来自 C 标准,6.3.1.8 常用算术转换,强调我的:

Many operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to determine a common real type for the operands and result. For the specified operands, each operand is converted, without change of type domain, to a type whose corresponding real type is the common real type. Unless explicitly stated otherwise, the common real type is also the corresponding real type of the result, whose type domain is the type domain of the operands if they are the same, and complex otherwise. This pattern is called the usual arithmetic conversions:

  • First, if the correspeonding real type of either operand is long double...
  • Otherwise, if the corresponding real type of either operand is double...
  • Otherwise, if the corresponding real type of either operand is float...
  • Otherwise, the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:
    • If both operands have the same type, then no further conversion is needed.

所以你是完全正确的。表达式 'a' + (char) 5 的类型是 int。除非用户明确要求,否则不会重铸回 char。请注意,此处的 'a' 的类型为 int,因此只有 (char)5 需要提升。这是6.4.4.4字符常量中规定的:

An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in 'x'.
...
An integer character constant has type int.

有一个示例演示了显式重铸为 char:

In executing the fragment

char c1, c2;
/* ... */
c1 = c1 + c2

the ‘‘integer promotions’’ require that the abstract machine promote the value of each variable to int size and then add the two ints and truncate the sum. Provided the addition of two chars can be done without overflow, or with overflow wrapping silently to produce the correct result, the actual execution need only produce the same result, possibly omitting the promotions.

这里的截断只是因为我们分配回一个char

关于c++ - C 如何处理 char 和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30035547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com