C11隐式转换字符,x%y

时间:2017-06-28 06:23:43

标签: c

在C11中,

char foo(char x, char y) {
    return x % y;
}

是否在任何地方进行了隐式转换(例如提升为int)?

3 个答案:

答案 0 :(得分:5)

通常的算术转换适用于%的操作数,与它们应用于其他乘法和加法运算符的操作数的方式相同(参见6.5.5 Multiplicative operators)。

操作数会提升到intunsigned int,具体取决于您平台上char类型的范围(请参阅6.3.1.8 Usual arithmetic conversions6.3.1.1 Boolean, characters, and integers

在大多数真实平台上,操作数将提升为int,因为int的范围通常涵盖char的整个范围。在一个或多或少的异国情调的平台上,sizeof(char) == sizeof(int)char是无符号类型(意味着char的范围不适合int的范围),他们将被提升为unsigned int

答案 1 :(得分:2)

%运营商的操作数要求为 n1570-§6.5.5(P2):

  

%运算符的操作数应具有整数类型

在这种情况下,通常的算术转换将在两个操作数上进行,因为char被提升为unsigned int

答案 2 :(得分:0)

是的,char通常被提升为int或unsigned int,但是如果解释器可以证明结果是相同的,那么可以直接使用chars进行计算:

引用标准5.1.2.3 Program execution

  

11示例2执行片段

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

''整数促销''要求抽象机器推广   每个变量的值为int size然后添加两个int和   截断总和。

     

Provided the addition of two chars can be done without §5.1.2.3 Environment 15ISO/IEC 9899:201x Committee Draft — April 12, 2011 N1570 overflow, or with overflow wrapping silently to produce the correct result, the actual execution need only produce the same result, possibly omitting the promotions