Here is another C code snippet question. Consider the following piece of code, and spot if there is a problem in it or not.

#include <stdio.h>

int main (void)
{
  int x = 5;
  +x += 1;
  printf ("%d\n", +x);
  return 0;
}

The answer is yes, there is a problem in it. The problem is in the line 6. +x += 1;. This is because the +x evaluates to the value stored in x, as in C99 Section 6.5.3.3 Paragraph 2, and the evaluation result is not a modifiable l-value. The += falls inside the assignment operate category. Any assignment operator requires a modifiable l-value as its left operand, clearly stated in C99 Section 6.5.16 Paragraph 2. Therefore the line results in a compilation error. In gcc I get:

test_file.c:6:6: error: lvalue required as left operand of assignment

In the same note, here is another similar piece of code.

#include <stdio.h>

int main (void)
{
  int x = 5;
  int y = 10;

  (x = y) += 1;

  printf ("%d\n", x);
  return 0;
}

The problem is in line 8. As per C99 Section 6.5.16 Paragraph 3

An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue.

Therefore, after first evaluating (due to the braces) of x = y, an assignment operation is attempted to be made on a non l-value, which again results in a compilation error. Remove braces and it compiles fine, as the += executes first and assigns the modified value of y to x .

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s