shreyasva
shreyasva

Reputation: 13526

Expression in C++

int main() {
  int a = 10;
  int b = a * a++;
  printf("%i %i", a, b);
  return 0;
}

Is the output of the above code undefined behavior?

Upvotes: 2

Views: 117

Answers (1)

sharptooth
sharptooth

Reputation: 170549

No in

int b = a * a++;

the behavior is undefined, so the result can be anything - that's not what "implementation dependent" means.

You might wonder why it's UB here since a is modified only once. The reason is there's also a requirement in 5/4 paragraph of the Standard that the prior value shall be accessed only to determine the value to be stored. a shall only be read to determine the new value of a, but here a is read twice - once to compute the first multiplier and once again to compute the result of a++ that has a side-effect of writing a new value into a. So even though a is modified once here it is undefined behavior.

Upvotes: 6

Related Questions