1

Please have a look at the following code:

#include<stdio.h>
int main()
{
    if(sizeof(int)>-1)
    {
        printf("Condition evaluates to true !");
    }
    else
    {
        printf("Condition evaluates to false !");
    }
    return 0;
}

A newbie would expect the output to be "Condition evaluates to true !". Unfortunately it is not the one. Please why the hell this happens.

Rishav Raj
  • 13
  • 5
  • Turn the compiler warnings on, that will give you a clue about the comparison of `signed` and `unsigned` integers. – ereOn Jul 02 '14 at 05:40

1 Answers1

0

You need to cast the return of sizeof to int in order for the evaluation to be valid:

if((int)(sizeof(int)) > -1)

Look at the return type of sizeof

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • Thanks, but the main problem is, how will a novice programmer come to know that this is an issue of comparison of an unsigned and a signed integer ? I mean to say, that it appears that both values to the left and the to right of the "<" operator are integers. So how can one come to know about the cause behind evaluation of the expression to false ? I would appreciate if u tell me some resources to study about these and other subtle issues about C. Thank You ! – Rishav Raj Jul 02 '14 at 09:22
  • This is just one of those thing you have to get into a habit of doing to help move on from being a novice programmer :). When you first noticed that isn't write, your first instinct will become **check the returns** on all pieces that go into the problem. That would have taken you to your **bookmark** to the [**Gnu C-Manual**](http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#The-sizeof-Operator) You would find there: "The result of the sizeof operator is of a type called size_t, which is defined in the header file . size_t is an unsigned integer type". Now you know. – David C. Rankin Jul 02 '14 at 09:46
  • Thank You @david . But I would appreciate if u tell me about some resources where i get to study these or other subtle issues or some tricky problems of C, for practice and enriching my knowlege. – Rishav Raj Jul 03 '14 at 06:54
  • [The Gnu C-Manual](http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#The-sizeof-Operator) is a good one, the [Gnu C Programming Tutorial](crasseux.com/books/ctutorial/index.html) is another, the `man pages` installed on you computer are great! (they are a bit hard to get used to, but they contain numerous examples and definitions for every function, etc..) You have to be wary of internet programming sites. Some are very good, others just plain wrong. Just remember to verify what you get off the internet against the man pages or the Gnu manual. Good luck. – David C. Rankin Jul 03 '14 at 07:30