-5

What is the output of the following program?

#include <iostream>
using namespace std;

int main()
{
    int a = 2, b = 4;
    a++ = b;
    cout << a << b;
    return 0;
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Yatharth
  • 15
  • 5
  • 1
    Why don't you try it? – Michael Chourdakis Jun 26 '19 at 18:27
  • I don't want to found facetious but why not try running it? That's how to learn as a beginner. – user3344003 Jun 26 '19 at 18:27
  • 6
    [Not executed at all, can't compile](http://coliru.stacked-crooked.com/a/d86b0767833c7555). The result of a post increment operation doesn't result in a _lvalue_. – πάντα ῥεῖ Jun 26 '19 at 18:28
  • 1
    I'd agree with that "Just try it!" if not for Undefined behaviour and compiler extensions. Sometimes "Just trying it" is inconsistent and outright wrong. – user4581301 Jun 26 '19 at 18:30
  • To previous commentators, trying it yourself is a terrible way of learning C++. You cannot deduce, just from the behavior, if the code is well formed or if it contains UB. C++ cannot be learned by trial and error. – François Andrieux Jun 26 '19 at 18:31
  • 2
    Some handy reading to help you parse the error message in the code link @πάνταῥεῖ provided: [What are rvalues, lvalues, xvalues, glvalues, and prvalues?](https://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues) – user4581301 Jun 26 '19 at 18:31
  • The idea of trying it yourself was not meant for him to learn C++, nor an implication to learn by trial and error. It was just a note on how this question is pointless here. – Michael Chourdakis Jun 26 '19 at 18:33

1 Answers1

5

This is not legal C++ code.

The statement

a++ = b;

is not legal. Intuitively, you can only place something on the left-hand side of an assignment expression if it represents an object, not a value. For example, we can't write

x + y = z;

because x + y is a value, not an object. The same principle is at play in your code: the expression a++ is not something that can be written to, as it means "change a by adding one to it, then produce the value that a used to have."

The comments on your question talk about the formal terms that are used to describe what I'm referring to here as "values" and "something can be written to." These are formally called lvalues, rvalues, prvalues, etc., and it might be worth looking into these to learn more about what sorts of assignment statements are legal.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065