Notes - C/C++ Sequence Points

The following conclusions are drawn for their own practice, not official documents


Look at the beginning of the code (environment vs2015):

#include<stdio.h>
#include<iostream>
using namespace std;


intmain()
{

	int x=0, y[5] = {};

	y[x] = x++ + x++ + ++x;
	cout << x <<" "<< y[0] << y[1] << y[2] << y[3] << y[4];
	system("pause");
}


Predict the result:

-->

-->

-->

-->

-->

-->

Above result:


Don't know the result is the same as your imagination?

y[x] = x++ + x++ + ++x;

We all know that ++x will be executed immediately, and x++ will be executed later. Since it is later, do you know when it will be later?

There is an abstract sequence point in C/C++ (not an actual thing, just a concept), sequence points include ":? , ; || && ", as well as function calls, and complete expressions, yes, x++ That is, it will keep dragging and dragging until the sequence point appears. ------ Concept 1

After knowing concept 1, let's push it, the initial value of x is 0, the original formula

y[x] = x++ + x++ + ++x; 		equivalent to 		y[x] = x + x + ++x ;++++

So after the operation of x + x + ++x, the value of x becomes 1, so the value of y[1] is changed, which is understandable, then why the value of y[1] becomes 3? Shouldn't it be 1? OK

Let's see, the value of x++ + x++ + ++x may be understood as the value of (x++) + the value of (x++) + the value of (++x), but it is not, the compiler will execute x++, x++ in turn ,++x,
Finally, when calculating the sum of the three of them, he calculates neither the value of (x++) + the value of (x++) + the value of (++x), nor the value of x + x + (++x), But the value of x + x + x, this time x has become 1,
So the value of the expression is 3 	------ Concept 2

In this way, the code is explained. In short, it is the above concept 1 and concept 2.

In order to sublimate Concept 1, a piece of code is introduced:

#include<stdio.h>
#include<iostream>
using namespace std;

intmain()
{
	int x, y, z;
	x = y = z = 0;
	++x || ++y && ++z;
	cout << x << " " << y << " " << z;
	system("pause");
}

Tell you the result directly:

1 0 0;


Specifically why it is 1 0 0, I only know the conclusion, I don't know why,

The conclusion is that when the logical or before is true, everything after the logical or is short-circuited, yes, yes, everything, no matter how many things follow

even if

++x || ++y && ++z || ++p && ++q || ++r

It will only execute ++x, and nothing after that.

give a link at the end


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326423824&siteId=291194637