Reputation: 33
suppose we have a function declared as the following:
void myFunct(unsigned char a);
In my main program i call it this way myFunct(5000)
and i get this warning:
"integer conversion resulted in truncation".
The compiler warned me that i passed a value larger than 255.
Anyway, if a declare a variable const ulong test = 5000
and i pass it to myFunct myFunct(test)
, the compiler does not warn me about the same possible issue.
Can anyone explain me this behaviour?
This missing warning caused an annoying bug in my code and i am now afraid that these kind of issues could be present elsewhere.
I've tried different compilers like MinGW and GHS Version 5(GreenHills) and both did not warn me about the reported issue.
Can anyone tell me if there is a way to prevent such problems?
Upvotes: 3
Views: 699
Reputation: 80305
There does not need to be any logic to compiler warnings. Compilers try to produce useful warnings about issues you may want to know about, and to avoid wasting your time with false positives. Any heuristic that satisfies this two conflicting goals may be implemented in a compiler.
The most likely explanation here is that in myFunct(5000)
, it is obvious that the conversion fails to preserve the value, whereas in myFunct(test)
, it is not obvious looking only at the function call. Warning about the latter would require knowing the value of test
at that point, and the compiler may not have the mechanisms to determine that the value of test
at that point it 5000
.
Although it is obvious that the value of test
is always 5000
in this particular example, the fact that a mechanism to predict the values of variables wouldn't work well in all cases (non-const variables the values of which are difficult to predict) may discourage compiler writers to even attempt to implement such a warning.
Static analyzers settle for different goals than compilers. They try to predict values of variables in at least the easy cases, and some of them may be configurable to warn for myFunct(test)
in your example. Most static analyzers still reserve the right not to warn if they aren't certain that a problem is present, and you never know what they will be certain about or not. But you would have a better chance of getting a warning with a static analyzer than with a compiler.
Note that what happens to the argument of myFunct
in myFunct(5000)
is a conversion. A cast is a syntactic construct. There is no such thing as an “implicit cast”.
Upvotes: 4