-1
int main() {
    int a = 100000;
    char b;
    b = a;
}

I assumed that this code wouldn't compile, but it does. Could someone give me a solid explanation of how c handles implicit type conversion?

1 Answers1

-1

C is not type safe. It heavily relies on the user and therefore assumes he knows what he's doing.

This assignment is implementation dependent ìnt and will assign the least significant byte to the char variable.

Assuming the size of an int of your host architecture is 32 bits, and being your ìnt by default signed, then the range the ìnt can store is of

[-1 * (2^(32 - 1) -1) , 2^(32 - 1)] = [-2147483647, 2147483648]

Compare that to the range that an unsigned char can store (depends on host architecture but char usually being 8-bit long):

[0, 255]

You can think of char as being an integer limited to that range. It might get confusing since it is commonly used to store characters.

  • 7
    If the `char` is signed, and the `int` one can't fit `char` (and it can't given the value), the result will be implementation defined. – Eugene Sh. Nov 02 '17 at 20:29
  • 1
    *All what will happen is that this assignment will truncate the `ìnt` value so it can fit in the `char` variable.* No, as @EugeneSh. states, see http://port70.net/~nsz/c/c11/n1570.html#6.3.1.3p3 – Andrew Henle Nov 02 '17 at 20:33
  • 1
    *"char always being 8-bit long"* – The C standard does not mandate that, compare https://stackoverflow.com/questions/9727465/will-a-char-always-always-always-have-8-bits (POSIX however does). – Martin R Nov 02 '17 at 20:36
  • *`char` always being 8-bit long* Not correct. Per [**5.2.4.2.1 Sizes of integer types **](http://port70.net/~nsz/c/c11/n1570.html#5.2.4.2.1): "Their implementation-defined values shall be **equal or greater in magnitude (absolute value)** to those shown ..." – Andrew Henle Nov 02 '17 at 20:37
  • To be clear: "... will assign the least significant byte to the char variable." is not specified by C. It is only an ID possibility. The conversion/assignment is "implementation-defined or an implementation-defined signal is raised." – chux - Reinstate Monica Nov 02 '17 at 20:59
  • Off by 1 : at least once. `[-1 * (2^(32 - 1) -1) , 2^(32 - 1)] = [-2147483647, 2147483648]` is certainly incorrect. Integer max values are always a power-of-2 minus 1 – chux - Reinstate Monica Nov 02 '17 at 21:01
  • @chux: char is sometimes unsigned. – rici Nov 02 '17 at 22:12
  • @rici True, when `char` is _unsigned_, the conversion/assignment is well defined. No UB. – chux - Reinstate Monica Nov 02 '17 at 23:07