Bug 37800 - decrementation problem - different result in similar situations
Summary: decrementation problem - different result in similar situations
Status: RESOLVED DUPLICATE of bug 11751
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.2.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
Depends on:
Reported: 2008-10-10 16:27 UTC by Mark Poks
Modified: 2008-10-10 17:17 UTC (History)
57 users (show)

See Also:
Known to work:
Known to fail:
Last reconfirmed:


Note You need to log in before you can comment on or make changes to this bug.
Description Mark Poks 2008-10-10 16:27:05 UTC
compiled with no any special arguments: g++-4.2 test.cpp
operating system: Linux/Debian 4 (lenny)

foo(++i, i-1);

i've read non-bugs, but there was no exacly about my situation.

example code:

#include <stdio.h>

void func(int* a, int* b) {
	printf("%d %d\n", *a, *b);

int main() {
	int foo[]={1,2,3};
	int *p;

	p = foo + 1;	// set pointer to point at '2'
	func(++p, p);   // result: 3 3 (same at msvc and same as gcc)
                        // OK

	p = foo + 1;
	func(++p, p - 1); // result at msvc: 3 2., result at gcc: 3 1
                          // BAD: p variable at second argument isn't yet 
                          // incremented

cheers, Mark
Comment 1 Paolo Carlini 2008-10-10 16:33:54 UTC

*** This bug has been marked as a duplicate of 11751 ***
Comment 2 Mark Poks 2008-10-10 16:57:41 UTC
i'm not really sure why there maight be a difference in incrementation behavior between:

        foo(++p, p);

        foo(++p, p - 1); 

looking at the code it is obvious that '++p' is a first operation and the 'p' or in second example a 'p-1' is a second operation. both operations are done before call to a foo. isn't it?

so why behaviour of second example is that 'p-1' is executed first and than '++p'?

note that in other compillers (m$vc), not mentioning other languages (java), behavious of exampled code is obvious and clear.

Comment 3 Paolo Carlini 2008-10-10 17:06:07 UTC
(In reply to comment #2)
> isn't it?

What you or I believe doesn't matter here, the specifications in the C / C++ Standard do. If you want to write portable code simply you can't rely on that order. If you want to learn more about those issues, just google for sequence points, as already mentioned elsewhere.
Comment 4 Paolo Carlini 2008-10-10 17:17:10 UTC
By the way, those two cases, *both* lead to undefined behavior. I would recommend you using -Wsequence-point more frequently.