Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned char automatically promoted to int in function call, why?

Tags:

People also ask

What is the purpose of unsigned char?

Unsigned char data type in C++ is used to store 8-bit characters. A maximum value that can be stored in an unsigned char data type is typically 255, around 28 – 1(but is compiler dependent).

Can char be promoted to int?

Some data types like char , short int take less number of bytes than int, these data types are automatically promoted to int or unsigned int when an operation is performed on them. This is called integer promotion.

Why do we need signed and unsigned char?

Use only signed char and unsigned char types for the storage and use of numeric values because it is the only portable way to guarantee the signedness of the character types (see STR00-C. Represent characters using an appropriate type for more information on representing characters).

What is integer promotion?

Integer promotion is the implicit conversion of a value of any integer type with rank less or equal to rank of int or of a bit field of type _Bool, int, signed int, unsigned int, to the value of type int or unsigned int.


Why is an unsigned char automatically promoted to an int when calling a function? In the example below there is an f(int) and a f(char) function. It seemed more logical that the compiler would coerce an unsigned char argument to a char and call f(char) since they have the same number of bits. It is calling f(int) instead, even when that means promoting the argument to a type with more bits. Any pointers to where the rule is defined? Standard or compiler/platform specific?

#include <iostream>

void f( int key )
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

void f( char key )
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main( int argc, char* argv[] )
{
    int a = 'a';
    char b = 'b';
    unsigned char c = 'c';

    f(a);
    f(b);
    f(c);

    return 0;
}

Produces this output:

void f(int)
void f(char)
void f(int)