unsigned char在函数调用中自动提升为int,为什么? [英] Unsigned char automatically promoted to int in function call, why?
问题描述
为什么调用函数时 unsigned char
自动提升为 int
?在下面的例子中有一个 f(int)
和 f(char)
编译器将 unsigned char
参数强制转换为 char
并调用 f(char)
,因为它们具有相同的位数。它调用 f(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;
}
产生此输出:
void f(int)
void f(char)
void f(int)
推荐答案
因为 unsigned char
不能用 char
。例如,如果它们都是8位,并且你的unsigned char包含值 255
,溢出 signed char
- 和有符号整数溢出调用未定义的行为。无论如何,可打印字符通常预期存储在 char
而不是 unsigned char
(和C字符串类型 char []
,而不是 unsigned char []
等)
Because unsigned char
cannot be represented by char
. For example, if they're both 8 bits, and your unsigned char contains the value 255
, that overflows the signed char
- and signed integer overflow invokes undefined behavior. Anyway, printable characters are generally expected to be stored in char
and not unsigned char
(and C strings are of type char[]
and not unsigned char[]
, etc.)
因此,需要提升到 int
来表示大于 1 < (CHAR_BIT - 1)
。
So the promotion to int
is necessary to represent values greater than 1 << (CHAR_BIT - 1)
.
这篇关于unsigned char在函数调用中自动提升为int,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!