Question

In gcc, adding or subtracting a constant to an integral type smaller than int results in an int.

#include <cstdint>
#include <cstdio>

int main()
{
    int8_t wat = 5;
    printf("%zd\n", sizeof(wat + 1));
    return 0;
}

gives 4. I noticed this when using a simple += statement with -Wconversion. With that warning flag set,

#include <cstdint>

int main()
{
    int8_t wat = 5;
    wat += 5;
    return 0;
}

gives

wat.cpp:7:6: warning: conversion to ‘int8_t {aka signed char}’ from ‘int’ may alter its value [-Wconversion]

Is there any way to suppress this warning? Why is this occuring? Casting doesn't seem to do the trick.

Was it helpful?

Solution

According to the C++ Standard

10 Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions,

The usual arithmetic conversion includes the integral promotion

1 A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

So in this expression

wat += 5;

that is equivalent to

wat = wat + 5;

wat in the right side of the assignment is converted to type int and the type of expression wat + 5 is int. As the range of values of type int is greater than of type int8_t the compiler issues the warning.

Also the message of the warning shows how to suppress the warning: [-Wconversion]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top