C++ basic type demotion when returning from a function

304 Views Asked by At

I'm getting a (expected)

warning: large integer implicitly truncated to unsigned type [-Woverflow]

on Get2() but on not on Get1(). I'm quite 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 templated code doing other things - without hard-coded values. The same happens in C++ when compiled either with GCC or Clang.

2

There are 2 best solutions below

1
On BEST ANSWER

The warning, which is reported on the Get2 function, is there because there's an implicit conversion (as opposed to the explicit one you have on Get1) happening, and the compiler is warning you that the integer is being truncated.

The explicit one is not being reported, because you have explicitly told the compiler that you are performing a truncation, so a warning would probably be redundant in that case.

0
On

Just to add to the answer by Mr Jefffrey,

from the return statement Semantics, C11, chapter §6.8.6.4

If a return statement with an expression is executed, the value of the expression is returned to the caller as the value of the function call expression. If the expression has a type different from the return type of the function in which it appears, the value is converted as if by assignment to an object having the return type of the function.

In case of Get1(), because of the explicit cast, the final expression type is uint8_t which matches the return type of the function.

In case of Get2(), the final expression type is uint64_t which does not matches the return type uint8_t of the function.

So, in case of Get2(), the type is getting converted (as if by assignment) and due to the mismtach in type, the warning is produced.