Incrementing number has weird results

Hi, all.
I am creating a code for executing a code from an sd card. I am working on compound operators and I am testing the incrementing function. When I execute the function the results are the same as the input. Here is the code:

int co(int a, String b, int c) {
  Serial.print("a");
  Serial.print(a);
  Serial.print("b");
  Serial.print(b);
  Serial.print("c");
  Serial.print(c);
  Serial.print("<" + String(a++) + ">");
  // Compound Operators
  if (b == "++") {return a++;}
  if (b == "--") {return a--;}
  if (b == "+=") {return a+=c;}
  if (b == "-=") {return a-=c;}
  if (b == "*=") {return a*=c;}
  if (b == "/=") {return a/=c;}
  if (b == "|=") {return a|=c;}
  if (b == "&=") {return a&=c;}
  if (b == "%=") {return a%=c;}
  if (b == "^=") {return a^=c;}
}

The Serial prints are for debugging and when I run this code I get this in the Serial Monitor: a15b++c15<15>16 The input number is 15 and the last 16 is the output of the function however when I comment out Serial.print("<" + String(a++) + ">"); it says this in the Serial Monitor: a15b++c1515

This means if I do the operation in the Serial Monitor before doing the final operation it shows the correct answer, otherwise it will say the input number. What do I do?

Try ++a instead of a++.

2 Likes

Thanks so much. I checked on the arduino reference and it says x++ increments x by 1 but returns the old value of x and ++x increments x by 1 and returns the new value.

2 Likes

Sorry to ressurrect this, but this is correct, but not the entire story. In English,
return(++a); is "increment variable a, then return the value of variable a",
return(a++); is "return the value of variable a, then increment{usually uselessly} the variable a"

Results/implications dependent on variable a's value due to post-increment will vary depending upon whether a is a global variable, a static(persistent) variable, or a volatile variable that is dismissed at the end of the function.

If a is a global, or static, you may take advantage of this trick, with a having a different value than that which is returned - or you may introduce a nasty and hard-to-locate bug. If it's volatile, no harm done, but no gain either, as the variable is immediately discarded due to returning from the function.

Hope this helps; others may chip in with more clarity wrt scoping rules, I'm no guru.

If we want to get pedantic, the variable might also be of a C++ type that has overloaded the definition of ++ to do something entirely different.

or a volatile variable that is dismissed at the end of the function.

be careful; I think you're using "volatile" in a way that doesn't match it's use in C and C++ (you probably mean "automatic" and/or "local/temporary")

1 Like

No intention of that. I'll leave that to others...

Simply pointing out a perfectly common wrinkle the OP didn't seem to be aware of.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.