chirilabogdan
asked on
pre/post increment
Under Solaris 5.8
#include<stdio.h>
int main()
{
int k;
k = 1;
k = k++ + ++k;
printf("%d", k);
return 0;
}
At:
cc file.c => result is 5
gcc file.c => result is 2
what result is good?
#include<stdio.h>
int main()
{
int k;
k = 1;
k = k++ + ++k;
printf("%d", k);
return 0;
}
At:
cc file.c => result is 5
gcc file.c => result is 2
what result is good?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Non of the result is good because this specified in C standard as an
undefined behavior which mean each compiler can produce any result as they
want.
The code is good for study C but don;t put it in any production code.
Don't write the code that you don't sure about the result.
undefined behavior which mean each compiler can produce any result as they
want.
The code is good for study C but don;t put it in any production code.
Don't write the code that you don't sure about the result.
I'd written that first example as an "intuitively, this is what one might think should happen". Then instead of veering off into the "this is what really should or could happen" I thought, "this is pretty weird -- what happens if you regroup the '+' symbols?"
Next thing you know, I'd completely missed that left turn at Albuquerque. ;)
Obvious, if (++k) is evaluated/executed prior to (k++) the results will be different.
Good catch, darlingm.
Kdo
I spoke with someone who has experience with compiler design.
I'm going to have to back the answer by c_wongsiriprasert.
----------
#include<stdio.h>
void f(int a, int b) {
printf("a = %d b = %d\n", a, b);
}
int main() {
int k = 1;
f(++k, ++k);
}
----------
output is "a = 3 b = 2"
weird, huh?
with f(k++, k++) instead
output is "a = 2 b = 1"
again, weird.
gcc seems to be doing the line from right to left...
I'm going to, at this point, strongly recommend only using one pre/post increment operater per line of code -- due to the ambiguity of compiler implementation.
I'm going to have to back the answer by c_wongsiriprasert.
----------
#include<stdio.h>
void f(int a, int b) {
printf("a = %d b = %d\n", a, b);
}
int main() {
int k = 1;
f(++k, ++k);
}
----------
output is "a = 3 b = 2"
weird, huh?
with f(k++, k++) instead
output is "a = 2 b = 1"
again, weird.
gcc seems to be doing the line from right to left...
I'm going to, at this point, strongly recommend only using one pre/post increment operater per line of code -- due to the ambiguity of compiler implementation.
I must admit that I never envisioned the statement:
k = k++ + ++k;
--------------------------
k = k++ + ++k;
k = (k+1) + (1+k);
k = (1+1) + (1+1);
k = 4
--------------------------
k = ((k++)++) + k;
k = ((k+1)+1) + k;
k = ((1+1)+1) + 1;
k = 4;
--------------------------
k = k + (++(++k));
k = k + (1+(1+k));
k = 1 + (1+(1+1));
k = 4;
No matter how the parsers evaluate the expression, it looks like both have their own problem....
Kdo