C11 implicit character conversion, x% y

In C11,

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

Is there any implicit conversion (like progressing to int) anywhere?

+3
c
source share
3 answers

The usual arithmetic transformations are applied to the operands of % in the same way as they are applied to the operands of other multiplicative and additive operators (see 6.5.5 Multiplicative operators ).

The operands are promoted either to int or to unsigned int , depending on the range of char type on your platform (see 6.3. 1.8 Ordinary arithmetic conversions and 6.3.1.1 Logical characters and integers )

On most real platforms, operands will advance to int since the int range usually spans the entire char range. On a more or less exotic platform, where sizeof(char) == sizeof(int) and char is an unsigned type (assuming that the char range does not fit into the int range), they will be upgraded to unsigned int .

+5
source share

The requirement for operands of the % operator is n1570-Β§6.5.5 (p2):

The operands of the % operator must be of integer type

In this case, the usual arithmetic conversion will be performed on both operands, since the char advances to unsigned int .

+2
source share

Yes, char is usually assigned to int or unsigned int, but it can be automatically calculated using characters if the interpreter can prove that the result will be the same:

Quote from the standard, 5.1.2.3 Program execution

11 EXAMPLE 2 When executing a fragment

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

"whole stocks" require an abstract machine to contribute to the value of each variable in int size, then add two ints and truncate the sum.

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 .

0
source share

All Articles