Skip to content

b=b++; It depends on the version of software #3570

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pjordi opened this issue Jul 22, 2015 · 5 comments
Closed

b=b++; It depends on the version of software #3570

pjordi opened this issue Jul 22, 2015 · 5 comments
Milestone

Comments

@pjordi
Copy link

pjordi commented Jul 22, 2015

This program with the version 1.0.5, b increases the value by 1, and with the version 1.6.5, b=0 all time.

int b=0;
void setup() {
Serial.begin(9600);
}

void loop() {
b=b++;
Serial.println(b);
delay(100);
}

@carlosperate
Copy link
Contributor

b=0 from 1.6.5 is the correct result, b++ should return the value before the increment takes place. Not quite sure why it wouldn't do the same in 1.0.5, sounds like it would be a way too notorious issue to be a bug in the compiler.

@bobc
Copy link
Contributor

bobc commented Jul 22, 2015

This is a classic C/C++ "gotcha".

b=b++ is "undefined behaviour". http://stackoverflow.com/questions/4968854/is-i-i-truly-a-undefined-behavior.

Undefined behaviour means the result depends on the compiler, as you have found, and both 1.0.5 and 1.6.5 are producing correct results, according to the standard.

You should change your code - to increment b, use one of "b++;" "b = b + 1;" or "b +=1".

@carlosperate
Copy link
Contributor

Wow, thanks @bobc , learning something new every day.

@Chris--A
Copy link
Contributor

It appears a large amount of reversal is occurring due to optimizations. Your case has popped up many times, however I have recently seen ordering differences in the way the compiler evaluates function parameters and even allocation of global addresses (#3061), which are implementation defined.

The key is to avoid assumptions. If you're unsure, stack overflow can be a big help, however the latest (free) standard can be accessed here :
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf

@facchinm
Copy link
Member

Thanks everyone for the clear explanation!

@ffissore ffissore modified the milestone: Release 1.6.6 Aug 3, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants