Quantcast
Channel: User Peter - Reinstate Monica - Stack Overflow
Viewing all articles
Browse latest Browse all 223

Answer by Peter - Reinstate Monica for Why is 'char -> int' promotion, but 'char -> short' is conversion (but not promotion)?

$
0
0

The promotions are a subset of conversions performed implicitly in certain circumstances, even if the target type is not given. Here are two of them:

  • Many built-in arithmetic operators "promote" their arguments to int if they are of lesser rank. The following program prints 256, because both chars are promoted to int before they are added, and the resulting expression has type int; by contrast, the second printf prints 0, because ++ does not promote its argument so that the 8 bit value overflows (which is defined for unsigned types).
#include <cstdio>int main(){    unsigned char c1 = 255, c2 = 1;    std::printf("%d\n", c1 + c2);    std::printf("%d\n", ++c1);}
  • Talking about printf: Integral arguments of lesser rank than int which do not have a corresponding parameter in the function declaration (like the second arguments in the printf calls above) are promoted to int. It is impossible to pass genuine chars to printf. (Note that in the second printf above, the expression ++c1 has type unsigned char, with the value 0, which is promoted to int when the argument is passed, but after the evaluation of the expression.)

Other widening conversions which are not promotions, like in unsigned short c = 'a';, are performed because the target of an assignment, the type of a formal parameter or an explicit conversion demand it.


Viewing all articles
Browse latest Browse all 223

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>