0
#include<stdio.h>
int main(){
int i;
// printf("%d",sizeof(i)) ;
printf("%d",(sizeof(i) > (-1))) ;
return 0;}

why does the code print 0 when sizeof(i) gives 4 in 64 bit OS? why does (sizeof(i) > (-1))) gives false(0) ?

  • 2
    Don't you also get a compiler warning? `sizeof()` returns an unsigned value, while -1 is signed. – PMF Mar 24 '22 at 16:45
  • The `sizeof` operator returns a value of type `size_t`, which is an *unsigned* type. So `-1` will be converted to a (very large) unsigned value. – Some programmer dude Mar 24 '22 at 16:45
  • 2
    When numbers are compared in C, they are first converted so that they are both the same type. In this example, they are both converted to an unsigned type, and so `-1` is converted to the largest possible unsigned number. – user3386109 Mar 24 '22 at 16:46
  • [Why](https://xyproblem.info/) are you trying to verify that sizeof returns a non-negative value in the first place? – jarmod Mar 24 '22 at 16:46
  • 3
    `sizeof` returns an `unsigned long long`, and `unsigned` means a non-negative value already. There's no need to compare it with `-1` in the first place. – The Coding Fox Mar 24 '22 at 16:53
  • Also [see this link](https://stackoverflow.com/questions/22047158/why-is-this-happening-with-the-sizeof-operator-when-comparing-with-a-negative-nu). – PaulMcKenzie Mar 24 '22 at 16:54
  • 3
    @SolvedGames It might be an `unsigned long long`, or an `unsigned long`, or an `unsigned int`, or an `unsigned short`. All that's guaranteed is that `size_t` is an unsigned integer type with a bit-width of at least 16 bits. – Some programmer dude Mar 24 '22 at 16:56
  • FYI, the conditional operator is `? :`, as in `A ? B : C`, which evaluates `B` if `A` is true and `C` otherwise. `>` is a relational operator. I suppose one might think of it as testing a condition, but “conditional” and “relational” are the terms used in the C standard. – Eric Postpischil Mar 24 '22 at 17:13

1 Answers1

3

Use a better compiler and enable warnings. Under any sane compiler you should have gotten a warning about comparing an unsigned and a signed value.

This should be closer to what you want:

printf("%d", (int)sizeof(i) > -1);

Or at least this:

printf("%d", sizeof(i) >= 0);

However your code is a no-op anyway, because it's impossible to have a negative size of a type.

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • Thanks a lot for your help.. I came across this when experimenting with the sizeof() to see what it does .. I thought it returns int .. thank you for the clarification... – Ankan Halder Mar 24 '22 at 17:00