Results 1 to 5 of 5
|
Enjoy an ad free experience by logging in. Not a member yet? Register.
|
|
-
03-07-2011 #1
- Join Date
- Nov 2009
- Posts
- 240
C/C++ Is this a gcc/g++ bug or...?
Please consider these lines of code and their outputs:
[CODE]
int C = 0;
fprintf(stdout, "\n(C, ++C) Bef = %d, Aft = %d\n\n", C, ++C);
fprintf(stdout, "(C++, C) Bef = %d, Aft = %d\n", C++, C);
if (C++ < C)
fprintf(stdout, "\nC++ (%d) < C(%d) \n", C, C);
else
fprintf(stdout, "\nC++ (%d) >= C(%d) \n", C, C);
if (C < ++C)
fprintf(stdout, "\nC (%d) < ++C(%d) \n", C, C);
else
fprintf(stdout, "\nC (%d) >= ++C(%d) \n", C, C);[\CODE]
[\CODE]
This produces the following outputs:
(C, ++C) Bef = 1, Aft = 1
(C++, C) Bef = 1, Aft = 2
C++ (3) >= C(3)
C (4) >= ++C(4)
The only one that looks right to me is the second one. I get similar results using both gcc and g++. Am I looking at a bug in these compilers or have I missed something in the docs?
TIA - Regards VP
-
03-07-2011 #2
this isn't a bug
the order in which those operations will be executed is non-deterministic, so your output may vary depending on what the compiler decides to do
-
03-07-2011 #3
- Join Date
- Nov 2009
- Posts
- 240
Solved
After my post, I did some more digging in my paper-based library.
I went back to some original specs of the C language (original books of Kernighan and Ritchie) and there was a comment re the fact that "it is not defined whether the compiler will always evaluate arguments left to right or vice versa...".
So if you use something like func(A, A++), you are not certain what values for A will be passed.
Thanks anyhow.
Cheers - VP
-
03-07-2011 #4
- Join Date
- Nov 2009
- Posts
- 240
Cheers coop. Didn't see your post
VP
-
03-08-2011 #5
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, in Chicago, or in a galaxy far, far away.
- Posts
- 14,038
This is a common mistake made by a lot of inexperienced C/C++ programmers. Caveat Programmer: the order of evaluation of arguments in a function is dependent upon the compiler. The standards allow them to be left to right, or right to left, at the discretion of the compiler authors, or any other way they choose...
So, the rule to follow is, don't use variable modifiers in function arguments IF the variable is going to be used elsewhere in the argument list, or in the function itself (such as if you pass a pointer or reference to the variable into the function). FWIW, I have spent many a "happy" day (and long weekend) debugging other people's code with such mistakes when the software that worked fine on one system, was broken on another! Cross-platform development leads one to consider these things rather quickly...Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!