ccastingtype-conversion

C compilers default behavior with constants


Say I do the following:

char x;

x = x + 077;

In this situation does the constant 077 have a default type of int even though the expression is assigning to a char? From reading K&R I have inferred that the + operator has higher precedence than = and the 077 (octal) has a default type of int, thus the value of x is promoted to an int. Then the addition operation is performed and then the answer of converted back to a char and assigned to x. Is this correct?

Does the same behavior happen for the following two expressions?:

x += 077
x += 1

Also, what happens if the following is used in an expression:

(char) 14

Is 14 first an int by default which is then reduced to a char, or is it a char to begin with?

char x;

x = 14;

Also, in this case is 14 first an int which is then reduced to a char or is it a char to begin with?


Solution

  • 14, 1 and 077 are integer literals, and those are always int or some larger type, never a char. That type doesn't depend on the context. (See C99 §6.4.4.1 for the details on the actual type.)

    The compound assignment a += b behave exactly as the corresponding a = a + b expression, except that a is only evaluated once:

    (C99 §6.5.16.2/3) A compound assignment of the form E1 op = E2 differs from the simple assignment expression E1 = E1 op (E2) only in that the lvalue E1 is evaluated only once.