Small traps of A Compiler
Sometimes a platform runs correctlyProgramIn another platform. During platform migration, the most common problems may be the issue of byte order and alignment. This article records a small trap I have encountered before. Take a look at this sectionCodeWhat is the output?
# Include "stdio. H "char do_something (int * P) {* P = 5; return 'X';} void test1 (void) {char s [] =" abcdef "; int Index = 0; s [Index] = do_something (& Index); printf ("% s/n", S) ;}int main (void) {test1 (); return 0 ;}
If we use the VC or arm compiler, the output is abcdex. If GCC is used, the output is xbcdef. The key lies in this sentence:
S [Index] = do_something (& Index );
The index on the left of the equal sign is changed on the right of the equal sign. The VC and arm compilers use the changed index (value: 5), and the GCC compiler uses the changed index (value: 0 ). Of course, the code I actually encountered is much more complicated. Finding this line of code in tens of thousands of lines of code is not a pleasant thing. In fact, the best way to solve such a compiler trap is: Do not write statements that may produce ambiguity. In this example, we should remember:
- In the value assignment statement, the array index or pointer offset used on the left side of the equal sign should not be changed on the right side of the equal sign.
Have you ever encountered a similar trap?