Thread: this is confusing :(

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    31

    this is confusing :(

    i came across this small code
    Code:
           #include <stdio.h>
    
           main()
    
           {
    
               if (sizeof(int) > -1)
    
                   printf("True");
    
               else
    
                   printf("False");
    
           }
    it evaluates as false. i thot sizeof int ought to be 4 so is "4 greater than -1" not true? However, when i first save sizeof int in a variable int x and then make comparison it evaluates as true.

    why ?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well sizeof returns a size_t type, which is usually unsigned.

    > if (sizeof(int) > -1)
    So you're comparing an unsigned with a signed, what do you think should happen?

    What happens is your -1 is recast into being the largest possible positive unsigned value, so the comparison is false.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    The complete code should look like this:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        if (sizeof(int) > -1)
            printf("True\n");
        else
            printf("False\n");
        return 0;
    }
    Havn't you receive a warning?
    My compiler throw one:
    Code:
    $ gcc -Wall -Wextra test.c -o test
    test.c: In function ‘main’:
    test.c:5:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
         if (sizeof(int) > -1)
                         ^
    This means, your comparison should be:
    Code:
        if ((int) sizeof(int) > -1)
    This cast the unsigned value from sizeof to an signed integer.
    Last edited by WoodSTokk; 05-30-2017 at 01:05 PM.
    Other have classes, we are class

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Confusing!!!
    By csreddy in forum C Programming
    Replies: 10
    Last Post: 06-26-2007, 07:00 AM
  2. Arrays are confusing...
    By GavinHawk in forum C Programming
    Replies: 10
    Last Post: 11-29-2005, 01:09 AM
  3. Confusing pointer
    By vaibhav in forum C++ Programming
    Replies: 9
    Last Post: 11-13-2005, 05:52 PM
  4. Confusing Pointer
    By loko in forum C Programming
    Replies: 4
    Last Post: 08-29-2005, 08:52 PM
  5. Confusing
    By John in forum C Programming
    Replies: 10
    Last Post: 08-19-2002, 02:01 PM

Tags for this Thread