Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment and usage in the same expression

Tags:

c++

I encountered a line of code:

int a = 10;
int b = 40;
a = a + b - (b = a);
cout << a << "   " << b << endl;

I cannot understand what happens in this code. Can anyone explain for me?

like image 734
Rocky Avatar asked Jul 22 '11 08:07

Rocky


People also ask

Can variables be assigned and declared in the same statement?

It is also possible to declare a variable and assign it a value in the same line, so instead of int i and then i = 9 you can write int i = 9 all in one go. If you have more than one variable of the same type you can also declare them together e.g.

What is the relationship between assignment and expression statement?

An assignment statement always has a single variable on the left hand side. The value of the expression (which can contain math operators and other variables) on the right of the = sign is stored in the variable on the left.

What is the difference between assignment and expression?

In Java, an assignment statement is an expression that evaluates a value, which is assigned to the variable on the left side of the assignment operator. Whereas an assignment expression is the same, except it does not take into account the variable.

What is variable and assignment?

A variable is a string of characters and numbers associated with a piece of information. The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”.


2 Answers

Undefined behavior. the value of b is changed and used for computation without an intervening sequence point. The results of the program are unpredictable - it can print anything or crash, or do do some nasty system calls.

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.53) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

like image 160
Armen Tsirunyan Avatar answered Oct 19 '22 23:10

Armen Tsirunyan


Undefined behavior

http://en.wikipedia.org/wiki/Sequence_point

like image 1
Vivek Goel Avatar answered Oct 19 '22 23:10

Vivek Goel