Skip to content

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

Closed
@pjordi

Description

@pjordi

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);
}

Activity

carlosperate

carlosperate commented on Jul 22, 2015

@carlosperate
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

bobc commented on Jul 22, 2015

@bobc
Contributor

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

carlosperate commented on Jul 22, 2015

@carlosperate
Contributor

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

Chris--A

Chris--A commented on Jul 23, 2015

@Chris--A
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

facchinm commented on Jul 23, 2015

@facchinm
Member

Thanks everyone for the clear explanation!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @ffissore@bobc@carlosperate@Chris--A@facchinm

        Issue actions

          b=b++; It depends on the version of software · Issue #3570 · arduino/Arduino