Why there is no overflow warning when converting int to char

int i=9999; char c=i; 

gives warning of overflow until

 char c=9999; 

gives

warning C4305 initializing truncation from int to char

why there is no overflow warning when converting int to char ?

0
source share
2 answers

You will get C4244 warning when compiling with / W 4 (which you should always do).

warning C4244: 'initializing': conversion from ' int ' to ' char ', possible data loss

+9
source

Regardless of whether any code construct creates a warning, the ability of the compiler and the choices made by its authors.

 char c=9999; 

9999 is a constant expression. The compiler can determine by simply analyzing the ad without additional context so that it overflows. (Presumably, a regular char signed, if it is unsigned, the conversion is correctly defined, but the compiler can still warn about this.)

 int i=9999; char c=i; 

This has the same semantics, but for the compiler to warn about the initialization of c , he should know that i has a value of 9999 (or at least a value outside the char range) when parsing this declaration. Suppose you wrote instead:

 int i = 9999; i = 42; char c = i; 

Then it is clear that no warning would be necessary or appropriate.

As James McNellis's answer indicates, a smart enough compiler can warn of all cases if it performs additional analysis of what happens during program execution. For some compiler, this helps turn on optimization, since the analysis needed to optimize the code (without removing it) can also reveal this potential runtime error.

I note that this is the answer to the question you asked: why there is no warning. The answer you accepted concerns the implied question: "I need a warning here, how can I turn it on?" I'm not complaining, just watching.

+1
source

Source: https://habr.com/ru/post/1480270/


All Articles