+5

why a negative signed char is bigger than a signed Int?

logically 23 is bigger than - 23 so why here the result is different? #include <stdio.h> int main() { unsigned int a=23; signed char c=-23; if(a>c) printf("%d",a); if(a<c) printf("%d",c); return 0;} // output - 23

c++ c

2/6/2020 6:08:10 AM

{ SorousH }

3 Answers

New Answer

+7

{ SorousH } I suspect the signed char might be getting converted to an unsigned char in the conditional statements. This could be a compiler specific behavior on comparison operators with mixed signed operands like this. If this is what is occurring, then the -23 signed char would be converted to an unsigned char which still supports 256 total values. However, the supported range changes from (-128 to 127) to (0 to 255). Since -23 isn't supported, the value would become: 233 => 256 - 23. Here, we see (23 < 233) or (a < c).

+5

Negative numbers have their first bit set to 1 so they are usually larger than positive numbers. C++ should be more strict with this, comparing unsigned and signed values is usually nonsense. https://code.sololearn.com/cUxBYa65ULzb/?ref=app

+2

David Carroll I suspected the same but was hesitant to answer. Also the signed char has top limit of 127 so if we add even 1, it gives -128 again, so 127 + 106 = -23 or 233 as you mentioned.