I have a recursive function that accepts an integer value. Everytime the function is called the value passed is incremented. If I use the postincrement operator the value is not incremented but if I use preincrement it is. Why is this?
I have a recursive function that accepts an integer value. Everytime the function is called the value passed is incremented. If I use the postincrement operator the value is not incremented but if I use preincrement it is. Why is this?
silk.odyssey
Let me be the first the make a wild guess as to what the code looks like:
foo(i++); vs foo(++i);The first one increments i then calls foo(i), the second one calls foo(i) then increments i.
gg
>Everytime the function is called the value passed is incremented.
Save yourself problems like this and don't actually change the value, just pass it added by one:
This is even more important when you do something using val after the recursive call. If you didn't really want it incremented then you'll have issues:Code:recursive_func ( val + 1 );
Code:#include <iostream> using namespace std; // Uncomment for correct operation and compare //#define CORRECT void tabme ( int val ) { if ( val == 6 ) return; for ( int i = 0; i < val; i++ ) cout<<'\t'; cout<<"In: "<< val <<'\n'; #ifdef CORRECT tabme ( val + 1 ); #else tabme ( ++val ); #endif for ( int i = 0; i < val; i++ ) cout<<'\t'; cout<<"Out: "<< val <<'\n'; } int main() { tabme ( 0 ); }
My best code is written with the delete key.
i am not sure I understand why val + 1 produces a different result than ++val.
silk.odyssey
http://www.embedded.com/story/OEG20020429S0037
http://www.embedded.com/showArticle....icleID=9900661
EDIT:
Ignore this post. There is nothing undefined about either of:
which is lucky, since we use both constructs frequently.Code:foo(i++); foo(++i);
Technically, it turns out that in both constructs i is incremented before the function call. However, i++ returns the value of i before it is incremented while ++i returns the value of i after it is incremented.
It turns out there is a sequence point:
which means that all arguments and side effects must happen before the function call.Code:foo(sequence_point_here);
However, when two or more arguments are involved, there is no rule about order of evaluation.
Last edited by anonytmouse; 04-10-2004 at 08:26 AM.
>i am not sure I understand why val + 1 produces a different result than ++val
Because ++val changes val, val + 1 does not.
My best code is written with the delete key.