c language if statement with sizeof [duplicate] - c

This question already has answers here:
sizeof() operator in if-statement
(5 answers)
Closed 7 years ago.
#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?

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.

sizeof is an operator which returns the size and the returned value type is unsigned int.
Since unsigned is having higher rank than singed type, -1 is treated as unsigned number.
-1 in this case is treated as 0xFFFF.
Hence if (sizeof(int) > 0XFFFF) is evaluated to false.

If you write
if ( ( int )sizeof(int) > -1)
you will get the expected result that is True.
Operator sizeof returns a value of type size_t that corresponds to some implementation defined unsigned integer type.
From the C STandard (6.5.3.4 The sizeof and alignof operators)
5 The value of the result of both operators is implementation-defined,
and its type (an unsigned integer type) is size_t, defined in (and other headers).
The rank of size_t in any case greater than or at least equal to the rank of type int. It means that when the compiler need to determine the type of an expression it converts operand will lower rank to the type of the operand with higher rank. If operands have the same rank but one operand has unsigned integer type and other has signed integer type then the common type is unsigned int type.
Thus in the condition of the if statement
if ( sizeof(int) > -1)
-1 is converted to unsigned integer type size_t and due to its internal representation where all bits are set to 1 is freater than the value of sizeof( int )

Related

Why should be there the involvement of type promotion in this code?

In the code below the sizeof(int) will produce a signed int with a value of 4 bytes (suppose on a particular compiler) and -1 is also signed int, then my answer should be Yes but it displays No.
#include <stdio.h>
int main()
{
if (sizeof(int) > -1)
printf("Yes");
else
printf("No");
return 0;
}
Well it is the famous signed unsigned comparison. Here -1 which is signed number when compared to unsigned numbers - promoted to an unsigned number resulting in a big magnitude value (SIZE_MAX). So it is always false.
The explanation why there would be type promotion here when comparing:
From standard §6.3.1.8
Otherwise, if the operand that has unsigned integer type has rank
greater or equal to the rank of the type of the other operand, then
the operand with signed integer type is converted to the type of the
operand with unsigned integer type.
Also from §6.5.8 under relational operators
If both of the operands have arithmetic type, the usual arithmetic
conversions are performed.
And what sizeof returns?
Under The sizeof and _Alignof operators §6.5.3.4
The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is
size_t, defined in (and other headers).
And in section §7.19 under Common definitions
size_t which is the unsigned integer type of the result of the sizeof
operator;
To clarify a bit further when you are converting -1 to size_t it will have the value (Basically modulo SIZE_MAX+1)
SIZE_MAX+1+(-1)
Also from standard §6.2.5 (Explaining the conversion)
A computation involving unsigned operands can never overflow, because
a result that cannot be represented by the resulting unsigned integer
type is reduced modulo the number that is one greater than the largest
value that can be represented by the resulting type.

Can anyone explain why the following program outputs nothing? [duplicate]

This question already has answers here:
Why is −1 > sizeof(int)?
(4 answers)
Closed 6 years ago.
The following program compiles successfully but when i ran it ,it prints nothing when i initialize the for loop with -1 but when i initialize for loop with 0 it successfully traverse all the array.I want to ask that can we don't traverse the array when we initialize the for loop with negative value??
#include <stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23, 34, 12, 17, 204, 99, 16};
int main(void) {
int d;
//printf("%d",TOTAL_ELEMENTS);
for (d = -1; d <= (TOTAL_ELEMENTS - 2); d++)
{
printf("%d ",d);
printf("%d\n", array[d+1]);
}
return 0;
}
The result of sizeof operator is of type size_t, which is an unsigned type.
As a result, the type of TOTAL_ELEMENTS is also unsigned. When -1 is compared with it, it's converted to a big unsigned number. That's why d <= (TOTAL_ELEMENTS - 2) is false.
Here d <= (TOTAL_ELEMENTS - 2) operands are subject of usual arithmetic conversions (6.3.1.8). And actually integer promotions rules act in your case:
If both operands have the same type, then no further conversion is
needed.
Otherwise, if both operands have signed integer types or both
have unsigned integer types, the operand with the type of lesser
integer conversion rank is converted to the type of the operand with
greater rank.
Otherwise, if the operand that has unsigned integer type
has rank greater or equal to the rank of the type of the other
operand, then the operand with signed integer type is converted to the
type of the operand with unsigned integer type.
Otherwise, if the type
of the operand with signed integer type can represent all of the
values of the type of the operand with unsigned integer type, then the
operand with unsigned integer type is converted to the type of the
operand with signed integer type.
Otherwise, both operands are
converted to the unsigned integer type corresponding to the type of
the operand with signed integer type.
According to what you've got your code falls into clause #3, then your signed -1 is converted via rule (6.3.1.3):
Otherwise, if the new type is unsigned, the value is converted by
repeatedly adding or subtracting one more than the maximum value that
can be represented in the new type until the value is in the range of
the new type.
As result it becomes a very large unsigned value, that is surely greater than TOTAL_ELEMENTS - 2 and you'll never enter the loop.
This doesn't do what you think it does:
d <= (TOTAL_ELEMENTS - 2)
Instead, do this:
d <= int(TOTAL_ELEMENTS - 2)
Otherwise you've got a signed-vs-unsigned comparison, and your -1 becomes the largest possible size_t.
sizeof produces a result of size_t, which is unsigned. Compare a signed and unsigned type and you can only expect things to blow up.
To elaborate, when you try to use both signed and unsigned type in arithmatic operations, the signed type will be promoted to unsigned type, producing a huge number. Thus, the value of d , promoted to unsigned type, will fail to meet the condition d <= (TOTAL_ELEMENTS - 2);, hence the loop body will not execute.
For operators that expect operands of arithmetic type cause conversions. This pattern is called the usual arithmetic conversions. for this particular case, quoting the standard, chapter §6.3.1.8
Otherwise, the integer promotions are performed on both operands. Then the
following rules are applied to the promoted operands:
[...]
Otherwise, if the operand that has unsigned integer type has rank greater or
equal to the rank of the type of the other operand, then the operand with
signed integer type is converted to the type of the operand with unsigned
integer type.
and, regarding the rank,
The rank of any unsigned integer type shall equal the rank of the corresponding
signed integer type, if any.
Also, for reference, quoting C11, chapter 7.19, (emphasis mine)
size_t
which is the unsigned integer type of the result of the sizeof operator;
Hint: Enable compiler warning and it will point to your mistake.

Why the following code does print "S is Bigger" even though s is smaller? [duplicate]

This question already has answers here:
Comparison operation on unsigned and signed integers
(7 answers)
Closed 6 years ago.
Following snippet of code is not working as I expected, the output of the following program is "S is Bigger" when compiled with GCC in an Ubuntu machine. Although the variable s is -1 and which is clearly smaller than sizeof(buffer) which is 20. But still it prints S is Bigger.
Only logical assumption I can make is that C is converting the variable "s" to unsigned integer and using in "If" condition.
If My assumption is correct why C is doing that or if I am wrong why this snippet is giving this confusing output.
#include <stdio.h>
int main(void) {
int s = -1;
char buffer[20];
if(s > sizeof(buffer)){
printf("S is Bigger");
}
return 0;
}
From the answer to this question
It's safe provided the int is zero or positive. If it's negative, and size_t is of equal or higher rank than int, then the int will be converted to size_t and so its negative value will instead become a positive value.
sizeof() returns size_t
You are correct, the compiler converts s to the unsigned int data type size_t (which is the return value of sizeof operator). So the comparison become (on my system where size_t is 64 bit):
if (18446744073709551615 > 20)
which is clearly true ;)
This is part of the Implicit conversions defined by the standard. The relevant section is the "Usual arithmetic conversions" which is in 6.3.1.8 of the standard.
See also this post and this other post
Foundamental rules:
If both operands have the same type, no further conversion is needed.
If both operands are of the same integer type (signed or unsigned), the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
If the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type is converted to the type of the operand with unsigned integer type.
If the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

Why does the following code, having sizeof keyword give me 0 and not 1? [duplicate]

This question already has answers here:
sizeof() operator in if-statement
(5 answers)
Closed 8 years ago.
What's really happening here? The output now is "False":
#include <stdio.h>
int main()
{
if (sizeof(int) > any_negative_integer)
printf("True");
else
printf("False");
return 0;
}
If I change it to:
if (sizeof(int) < any_negative_integer)
the output is "True".
Update: the same question has already been asked, I could not find it before asking.
sizeof returns size_t which is unsigned and so -1 is being converted to a very large unsigned number. Using the right warning level would have helped here, clang with the -Wconversion or -Weverything(note this is not for production use) flags warns us:
warning: implicit conversion changes signedness: 'int' to 'unsigned long' [-Wsign-conversion]
if (sizeof(int) > -1)
~ ^~
For gcc you receive a similar warning using the -Wextra flag:
warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
if (sizeof(int) > -1)
^
For reference, we know size_t is unsigned from the draft C99 standard section 7.17 Common definitions which says:
size_t
which is the unsigned integer type of the result of the sizeof operator;[...]
Note, it does not specify anything else about the type, in my specific case it happens to be unsigned long but it does not have to be.
The conversion of -1 is due to the usual arithmetic conversion covered in section 6.3.1.8 Usual arithmetic conversions which says:
[...]
Otherwise, if the operand that has unsigned integer type has rank greater or
equal to the rank of the type of the other operand, then the operand with
signed integer type is converted to the type of the operand with unsigned
integer type.
Otherwise, if the type of the operand with signed integer type can represent
all of the values of the type of the operand with unsigned integer type, then
the operand with unsigned integer type is converted to the type of the
operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type
corresponding to the type of the operand with signed integer type.
So the only time -1 would not be converted to an unsigned value would be if int could represent all the values of size_t, which is not the case here.
Why -1 ends up being a large unsigned value, actually it ends up being being the max value of the unsigned type is due to section 6.3.1.3 Signed and unsigned integers which says:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or
subtracting one more than the maximum value that can be represented in the new type
until the value is in the range of the new type.49)
So we end up with:
-1 + (UMAX + 1)
which is:
UMAX
and thus end up with:
if (sizeof(int) > UMAX )
Because sizeof() returns a size_t, an unsigned type. Comparing signed and unsigned types can give surprising results due to implicit casting before the comparison.

Why the sizeof operator is giving unexpected result in c? [duplicate]

This question already has answers here:
sizeof() operator in if-statement
(5 answers)
Closed 8 years ago.
What's really happening here? The output now is "False":
#include <stdio.h>
int main()
{
if (sizeof(int) > any_negative_integer)
printf("True");
else
printf("False");
return 0;
}
If I change it to:
if (sizeof(int) < any_negative_integer)
the output is "True".
Update: the same question has already been asked, I could not find it before asking.
sizeof returns size_t which is unsigned and so -1 is being converted to a very large unsigned number. Using the right warning level would have helped here, clang with the -Wconversion or -Weverything(note this is not for production use) flags warns us:
warning: implicit conversion changes signedness: 'int' to 'unsigned long' [-Wsign-conversion]
if (sizeof(int) > -1)
~ ^~
For gcc you receive a similar warning using the -Wextra flag:
warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
if (sizeof(int) > -1)
^
For reference, we know size_t is unsigned from the draft C99 standard section 7.17 Common definitions which says:
size_t
which is the unsigned integer type of the result of the sizeof operator;[...]
Note, it does not specify anything else about the type, in my specific case it happens to be unsigned long but it does not have to be.
The conversion of -1 is due to the usual arithmetic conversion covered in section 6.3.1.8 Usual arithmetic conversions which says:
[...]
Otherwise, if the operand that has unsigned integer type has rank greater or
equal to the rank of the type of the other operand, then the operand with
signed integer type is converted to the type of the operand with unsigned
integer type.
Otherwise, if the type of the operand with signed integer type can represent
all of the values of the type of the operand with unsigned integer type, then
the operand with unsigned integer type is converted to the type of the
operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type
corresponding to the type of the operand with signed integer type.
So the only time -1 would not be converted to an unsigned value would be if int could represent all the values of size_t, which is not the case here.
Why -1 ends up being a large unsigned value, actually it ends up being being the max value of the unsigned type is due to section 6.3.1.3 Signed and unsigned integers which says:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or
subtracting one more than the maximum value that can be represented in the new type
until the value is in the range of the new type.49)
So we end up with:
-1 + (UMAX + 1)
which is:
UMAX
and thus end up with:
if (sizeof(int) > UMAX )
Because sizeof() returns a size_t, an unsigned type. Comparing signed and unsigned types can give surprising results due to implicit casting before the comparison.

Resources