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).
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.
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With