为什么编译器不为 size_t 的负值生成警告?

Why compiler doesn't generate warnings for negative value with size_t?

在下面的代码中,我使用 size_t 作为函数参数并传递了负值。我使用以下命令在 GCC(Linux) 上编译了程序。

g++ -Wall size.cpp -o size

GCC 编译成功,没有警告,但结果不是我期望的:

size_t : 18446744073709551615
int : -1

代码:

#include <iostream>

void func1(size_t i) 
{
  std::cout << "size_t : " << i << std::endl;
}

void func2(int i) 
{
  std::cout << "int : " << i << std::endl;
}

int main() 
{
  func1(-1);
  func2(-1);
  return 0;
}

为什么编译器不为 size_t 的负值生成警告?

因为 size_t 在 C++ 中总是无符号的:

The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.


Why doesn't compiler generate warning for negative value with size_t?

因为分配 size_t 负值会调用有符号到无符号的转换,这是明确定义的:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note]