0
#include <stdio.h>
int main()
{
    int i = 23;
    char c = -23;
    if (i < c)
        printf("Yes\n");
    else
        printf("No\n");
}

This segment of code executes the else block, but it executes the if block if we replace integer value with unsigned int i = 23. Printing these values with %x results in

  1. c=ffffffe9
  2. i=17

My question here is how unsigned ints and char variables gets stored in memory?

Samir Kape
  • 1,733
  • 1
  • 16
  • 19
  • 1
    In one of three ways stated here: http://port70.net/~nsz/c/c11/n1570.html#6.2.6.2 – Eugene Sh. Jun 04 '18 at 20:31
  • 1
    In addition to how the variables are stored in memory it is important how they are converted in expressions. – Peter - Reinstate Monica Jun 04 '18 at 20:38
  • 1
    Keep in mind, this is likely to behave differently depending on compiler or compiler settings. `char` has implementation defined signedness; it could be signed or unsigned. If it's signed, then the behavior is defined from then on; `i < c` is definitely false. If it's unsigned, then I believe `c` would officially have undefined value (though on most two's complement systems, it would likely have the value `256 - 23`), making `i < c` true (both types would be promoted to `unsigned int` for the conversion). Point is, there is no guarantee that negative characters even exist. – ShadowRanger Jun 04 '18 at 20:41
  • 1
    @ShadowRanger `unsigned char c = -23;` is well defined. Signed encoding used is irreverent here. – chux - Reinstate Monica Jun 04 '18 at 20:46
  • "How is a negative character stored in memory? " --> Curious, _why_ is the encoding important? It _value_, like any _signed integer_ type is -23. That should be enough. – chux - Reinstate Monica Jun 04 '18 at 20:52
  • Regarding unsigned int, see [Implicit type promotion rules](https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules) – Lundin Jun 04 '18 at 21:03

2 Answers2

1

This should help you understand it a bit better: Signed to unsigned conversion in C - is it always safe?

"The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file."

Enjoy! :)

Grue
  • 11
  • 3
1

When you compare two different types, your compiler will perform a cast to the most suitable one. But in your case, there is no good solution: either you loose the sign, or the precision.

What is happening is that your compiler is promoting your char to unsigned byte.

You should check if your char is negative prior comparing it to an unsigned to prevent this from happening.

Answering what you are actually asking, a negative character is stored in memory using its two's complement.

Josu Goñi
  • 1,178
  • 1
  • 10
  • 26