-2
#include<stdio.h> 
int main()
{
    int a = 10;
    ++a = 20;      
    printf("a = %d", a);
    getchar();
    return 0;
}

The output obtained for the above code is : a=20; when run as C++ code.

#include<stdio.h> 
int main()
{
    int a = 10;
    a++ = 20;      
    printf("a = %d", a);
    getchar();
    return 0;
}

This gives compilation error. What is the reason behind this?

Trinity
  • 17
  • 3
  • `++a = 20;` will not compile.which compiler using? – Jayesh Bhoi Jul 26 '14 at 13:06
  • 3
    The actual error message is "compilation error"? That sounds like a bug -- the compiler should have given a clear indication of what is wrong here. What compiler are you using? Try another, for a more expansive error message. – Jongware Jul 26 '14 at 13:08
  • Take a look at [this answer to a related question](http://stackoverflow.com/a/10654019/335858). – Sergey Kalinichenko Jul 26 '14 at 13:32

2 Answers2

6

You are compiling your program with a C++ compiler.

In C++, the result of pre-increment operator is a lvalue but the result of post-increment operator is not a lvalue.

In C, both pre-increment and post-increment operators are not lvalues so you cannot assign to the result of an increment operator.

As you can see C and C++ have different rules int this matter which is not surprising as they are different languages.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

The statement ++a = 20 or a++ = 20 is wrong and any good compiler would give errors. If you understand the C philosophy, a++ or ++a is a = a+1. So, ++a = 20 practically means a = a+1 = 20 which is ridiculous. These statements are to be used alone as shortcut to increment. Please go through Ritchie and Kernighan's classic book on the C language.

I assume that you are using C compiler

Madhurjya
  • 497
  • 5
  • 17