Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c language if statement with sizeof [duplicate]

#include <stdio.h>
main()
{
   if (sizeof(int) > -1)
       printf("True");
   else
       printf("False");
}

ANSWER:

False

but according to the logic sizeof(int) return 2 and if(2>-1) return 1 and it should print True.

Why it is behaving otherwise?

like image 804
Harish Avatar asked Aug 12 '15 06:08

Harish


People also ask

How do you use sizeof if?

The operands of the > operator in the if statement are sizeof(int) and -1 . sizeof(int) is of type size_t , which is guaranteed to be an unsigned integer. In practice, size_t will most likely be at least as big as unsigned int on any system out there. -1 is of type int , which is equivalent to signed int .

Does sizeof return an int in C?

sizeof(int) returns the number of bytes used to store an integer. int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.

What value does sizeof return in C?

sizeof returns size_t ( unsigned type) . You are comparing a signed int with an unsigned int . When a signed operand is compared with unsigned one, the signed operand get converted to an unsigned value.

Does sizeof return Size_t?

The result of the sizeof operator is of type size_t , an integral type defined in the include file <stddef.


1 Answers

First of all, the value produced by sizeof is of size_t which is unsigned type. NOTE

As the unsigned type is of higher rank than the signed type, while performing the comparison, as per the norms of the relation operator, the usual arithmetic conversions are performed, meaning the signed type is promoted to unsigned type.

In your case, the -1, when considered as unsigned, represent the highest possible unsigned value, thus, no wonder

 if (sizeof(int) > -1)

Evaluates to false.

Moral of the story: Attempted comparison between a signed and an unsigned is expected to produce weird result, just as in your case. You should enable compiler warning and try to solve the issues reported by the compiler.


NOTE:

From C11, chapter §7.19, <stddef.h>,

size_t
which is the unsigned integer type of the result of the sizeof operator.

like image 68
Sourav Ghosh Avatar answered Sep 22 '22 01:09

Sourav Ghosh