1

In the following code, I have used size_t as an function argument and passed negative value. I have compiled program on GCC(Linux) using following command.

g++ -Wall size.cpp -o size

GCC compiled successful without warning, but the results are not what I expect:

size_t : 18446744073709551615
int : -1

Code:

#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;
}

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

msc
  • 33,420
  • 29
  • 119
  • 214

1 Answers1

3

Since size_t is always unsigned in 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?

Because assigning size_t a negative value invokes a signed-to-unsigned conversion, which is well-defined:

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]

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • There are a lot of well-defined operations that yield warnings. E.g. `if(test = 1)` gives `warning: using the result of an assignment as a condition without parentheses [-Wparentheses]` at least with Clang C++ compiler. So being well-defined isn't a sufficient condition for not generating a warning. – z80crew Sep 08 '20 at 17:44