1
#include <iostream>
using namespace std;

int main()
{
    if(sizeof(int)> -1)
        cout<<"ok";
    else
        cout<<"not ok";

    return 0;
} 

Isn't size of int supposed to be 4, which should be greater than -1.

Biffen
  • 6,249
  • 6
  • 28
  • 36

1 Answers1

7

Two things:

  1. sizeof(int) can be any positive integral value. (I've worked on a system where sizeof(char), sizeof(int) and sizeof(long) were all 1 and were all 64 bit types.)

  2. The type returned by sizeof is an unsigned type. When comparing with -1, -1 is converted to an unsigned value, with a high magnitude. Almost certainly sizeof(int) will be less than that.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • shouldnt `sizeof(int)` be at least 4 to be compliant? – 463035818_is_not_an_ai Sep 08 '21 at 10:27
  • 2
    @463035818_is_not_a_number: Nope, the range of `int` needs to be -32767 to +32767. (C++20 widens that by 1). It can be the same range as `char`, if `char` is widened. And `sizeof(char)` *must* be 1. – Bathsheba Sep 08 '21 at 10:28
  • The conversion comes from _"[..] if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type."_ ([ref. 8.3 (1.5.3)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf)), isn't it? – Yun Sep 08 '21 at 10:36