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

标签 c++ c++11 gcc unsigned-integer 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]

关于c++ - 为什么编译器不为 size_t 的负值生成警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46968502/

相关文章:

C++:由于#include 循环,无法将对象实例传递给另一个类

c++ - OpenGL - 某些图形卡上的问题

c++ - boost::heap::arity,它是什么?

GCC的异常处理模型

c++ - 将鼠标悬停在 SDL2 上时更改文本颜色

c++ - 这些 MySQL 类如何链接?

c++ - C++ 中的内存仿函数包装器

c++ - 在 Clang 上禁用 "deletion of copy constructor when move constructor is avaliable"

ubuntu下编译头文件。我在终端中输入什么?

c - 我如何解决我的代码在linux mint上检查数据类型的大小(是带有gcc编译器的c语言)