if Size of integer is 4 in C, then why It’s showing me that it’s less than -1?
Due to the usual arithmetic conversions if in an expression one operand has an unsigned integer type and other has a signed integer type and the rank of the unsigned integer type is greater than or equal to the rank of the signed integer type then the operand with the signed integer type is converted to the unsigned integer type.
In the condition of this if statement
if(sizeof(int) > -1)
the expression sizeof( int )
has the unsigned type size_t
(that usually corresponds to the type unsigned long int
) the rank of which is greater than the rank of the type int
that is the type of the integer constant -1
;
So the expression -1
is converted to the type size_t
by propagating the sign bit and as a result is converted to a very big unsigned integer value.
Here is a demonstration program
#include <stdio.h>
int main( void )
{
printf( "( int )-1 = %d\n", -1 );
printf( "( size_t )-1 = %zu\n", ( size_t )-1 );
}
The program output is
( int )-1 = -1
( size_t )-1 = 18446744073709551615
In the condition of the second if statement
if((int)(sizeof(int)) > -1)
the both operands have the signed type int
due to the explicit casting the first operand to the type int
. So neither conversion takes place and the operand -1
has the negative value -1
.
Pay attention to that there is a nuance. In some implementations the size of the unsigned type unsigned long int
(or of size_t
) is equal to the size of the signed type signed long long int
.
In means that objects of the type signed long long int
are unable to represent all values of the type unsigned long int
.
So in expressions with operands of the type signed long long int
and the type unsigned long int
the both operands are converted to the type unsigned long long int
again due to the same usual arithmetic conversions. and if you will write for example
if ( sizeof(int) > -1ll)
where there is used the operand -1ll
of the type signed long long int
the rank of which is greater than the rank of the operand of the type size_t
nevertheless the condition again will be evaluated to false
because the operand -1ll
will be converted to the type unsigned long long int
.
Read more here: Source link