Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 5 of 5

Thread: increment operator bug with globals?

  1. #1
    Senior Member oddson's Avatar
    Join Date
    Feb 2013
    Location
    Isle in the Salish Sea
    Posts
    1,238

    increment operator bug with globals?

    Code:
    int i;
    
    void loop() {
      i=i++;
      Serial.println(i);
      delay(1000);
    }
    Doesn't increment.

    Ard. 1.8.5/ Td1.48

  2. #2
    Senior Member
    Join Date
    Apr 2014
    Location
    Germany
    Posts
    578
    That is correct. i++ is a post increment operator. I.e. it increments after the assignment. If you use ++i it should work.
    Anyway, you probably meant i++, instead of the unusual i = i++; ?

    Edit: actually it is undefined behaviour. (see https://stackoverflow.com/a/949443/1842762)

  3. #3
    Senior Member oddson's Avatar
    Join Date
    Feb 2013
    Location
    Isle in the Salish Sea
    Posts
    1,238
    Right. Bone-head

    I knew it works with locals but that's 'cause I use correctly there.

  4. #4
    Senior Member vjmuzik's Avatar
    Join Date
    Apr 2017
    Location
    Florida
    Posts
    425
    What would be the reasoning behind using i=i++ as opposed to just i++? For pointers I understand the difference, but I’m lost as far as regular variables go.

  5. #5
    Senior Member oddson's Avatar
    Join Date
    Feb 2013
    Location
    Isle in the Salish Sea
    Posts
    1,238
    Bone-head is the reason... I should think a bit before posting

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •