1

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?

Taylan Aydinli
  • 4,333
  • 15
  • 39
  • 33
SpruceMoose
  • 99
  • 1
  • 5

1 Answers1

2

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • How can `a` only be evaluated once if it is converted into an int and then back to a char as above? – SpruceMoose Dec 07 '13 at 09:32
  • Promotions and conversions aren't evaluations of `a`. (Imagine that `a` was not a variable but a function that returns a char (if that was possible in this context) - that function would only be called once with the `+=` operator. But twice with the `a=a+b` expression.) – Mat Dec 07 '13 at 09:35
  • So to clarify, what exactly is an _evaluation_ of `a`? – SpruceMoose Dec 07 '13 at 09:36
  • I think I've got it. See http://stackoverflow.com/questions/12133739/arithmetic-assignment-operator-left-side-evaluated-only-once – SpruceMoose Dec 07 '13 at 09:42