C ++ base type reduction when returning from a function
I get (expected)
warning: large integer implicitly truncated to unsigned type [
-Woverflow
]
on Get2()
, but not on Get1()
. I am very puzzled why:
#include <stdint.h>
uint8_t Get1()
{
return uint8_t(uint64_t(10000));
}
uint8_t Get2()
{
return uint64_t(10000);
}
int main()
{
return 0;
}
This is a simplified version of some boilerplate code that does other things - no hardcoded values. The same thing happens in C ++ when compiled with GCC or Clang.
source to share
The warning that is reported in the functionGet2
is because there is an implicit conversion (as opposed to an explicit one Get1
), and the compiler warns you that the integer is truncated.
The explicit message is not communicated because you explicitly told the compiler that you are truncating, so the warning would be redundant in that case.
source to share
To add to the answer from Jefffrey ,
from the return
Semantics instruction C11
, chapterยง6.8.6.4
If a statement is executed
return
with an expression, the value of the expression is returned to the caller as the value of the function call expression. If the expression is of a type other than the return type of the function in which it appears, the value is converted as if it were assigned to an object that has the return type of the function.
In the case Get1()
of an explicit cast, the type of the final expression uint8_t
matches the return type of the function.
In case, the Get2()
type of the final expression uint64_t
does not match the return type of the uint8_t
function.
Thus, in case the Get2()
type is converted (as if it were given), and because of the type mismtach in the type, a warning appears.
source to share