- 1
Test 1: Write the following code:
s1 = SQUARE1 (a);
cout<< "s1=" <<S1<<ENDL;
s2 = SQUARE2 (b);
cout<< "s2=" <<S2<<ENDL;
Result output:
S1=
S2=
You can see the same output , analysis:
S1 = SQUARE1 (a); Equivalent to
s1 = a*a;
So S1 is equal to the square of A;
s2 = SQUARE2 (b); The equivalent of
makes the SQYARE2 () function call First, B (5) as the argument pass, the function returns the value of 5*5, and then assigns the value to S2, so S2 is also equal to +
- 2
Test 2: Write the following code:
s1 = SQUARE1 (a+b);
cout<< "s1=" <<S1<<ENDL;
s2 = SQUARE2 (a+b);
cout<< "s2=" <<S2<<ENDL;
Result output:
S1=
S2=
You can see that the output is not the same , analysis:
S1 = SQUARE1 (a+b); Equivalent to
s1 = a+b*a+b;
The can see that # define is simply replaced, and because the operator has precedence, it gets
S1 = 5+25+5=35;
s2 = SQUARE2 (a+b); Equivalent to
First SQYARE2 () function call, a+b result 10 is passed as argument, the function returns the value of 10*10, and then assigns the value to S2, so S2 is also equal to 100.
Here involves the program Order Point knowledge, corresponding to this is a # define only simple substitution, the entire SQUARE1 (a+b) is followed by sequential points, For the SQUARE2 (a+b) defined by the inline, there are two sequential points, the first after A+b, and the second after the entire SQUARE2 (a+b) , which means that the program will perform the a+b operation first (Order point 1). The resulting results are then involved in the SQUARE2 () internal code operation (Order point 2).
- 3
Some might say that the following improvements can be taken to address the problem:
#define SQUARE1 (x) ((x) * (x )
It is true that the above problem is solved, but will there be other problems?
Look at the following Test 3:
- 4
Test 3: Write the following code:
S1 = SQUARE1 (a++);
cout<< "s1=" <<S1<<ENDL;
cout<< "a =" <<A<<ENDL;
s2 = SQUARE2 (b++);
cout<< "s2=" <<S2<<ENDL;
cout<< "b =" <<b<<endl;
Result output:
S1=
A = 7
S2=
B = 6
You can see the output of both is different , analysis:
S1 = SQUARE1 (a++); is equivalent to
s1 = a++*a++; because the suffix + + is incremented after use, so
S1 = 5*5 = Two
Then an increments of a=7
s2 = (= = = = = + = =). SQUARE2 (b++); Equivalent to
First SQUARE2 () function call, also because the suffix + + after the first use of the principle of increment, B, the initial value of 5 as an argument passed, the function returns the value of 5*5, and then assign the value to S2, so S2 equals;
Then b++ get b=6
Referring to the knowledge of the order Point described earlier, you will see that in this case #define increments the argument two times, and inline increments the argument one time , the problem persists even in the third step of the improvement, as described in the following test
- 5
The measured results are as follows:
#define SQUARE1 (X) x*x
- 6
#define SQUARE1 (x) ((x) * (x))
You can see that the problem with test 2 is resolved, but the test 3 problem persists
END