+ 2

Why the output is 'No' in the given code ?

unsigned int i = 23; signed char c = -23; if(i > c) printf("Yes"); else printf("No"); How the comparison between variable i & c is done here ?

22nd May 2020, 6:18 AM
Peter Parker
Peter Parker - avatar
4 Respostas
+ 6
A char can be either signed or unsigned and are signed by default having a range of -127 to 127. The issue is that i is unsigned, so when the comparison is made in the if statement the signed char c is implicitly cast to an unsigned int which causes an overflow resulting in the int value of c wrapping around to the upper bounds creating the overflow value to be higher than i. Remove the unsigned keyword and it will work as expected. You can also cast i to signed and it will work. Note, this could also cause issues if the unsigned value of i is greater than or less than the upper or lower bounds of c. Resulting in another overflow issue. if((signed)i > c) You can run the following code to see the overflow value of c when it is cast to an unsigned int. signed char c = -23; printf("%u", (unsigned)c);
22nd May 2020, 7:11 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
RenDev you can sign type char. A char is just an 8-bit integer number used to store...numbers. When you use %c (i.e. in printf ) the ascii symbol is shown... The only difference... https://code.sololearn.com/cFBC6ny0u19L/?ref=app
22nd May 2020, 9:39 AM
unChabon
unChabon - avatar
0
i think you cant sign char’s. chars are stored as hex and ranges from 0x00-0xFF, (or 0-255 if your working with base 10). Since there is no way a letter can be “negitive” per say, the negitve sign on the char is dropped and so -23 becomes 23 meaning that i=23 and c = 23 and 23 is not larger than 23 so it returns “no”
22nd May 2020, 6:48 AM
RenDev
RenDev - avatar
0
RenDev I executed this code with condition i >= c, still the output was no.
22nd May 2020, 6:59 AM
Peter Parker
Peter Parker - avatar