By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,987 Members | 971 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,987 IT Pros & Developers. It's quick & easy.

function not following usual Parameter Passing Sequence

P: n/a
Consider following code :

I have used code blocks for compiling.

output:
121 12
144 10

shouldn't the first line of output be 121 10 (considering the R-L passing of parameter)

Expand|Select|Wrap|Line Numbers
  1. int main(){
  2. int i=10,j=10;
  3. printf("%d%d\n",++i*i++,i);
  4. printf("%d%d",++j*j++,j++);
  5.  
  6. }
  7.  
Oct 14 '10 #1
Share this Question
Share on Google+
3 Replies


Meetee
Expert Mod 100+
P: 931
This is the magic of C/C++.

i = 10
++i = 11
++i*i++ = 121 and now i becomes 12 -> consider it as (++i*i) and then ++
Here compiler doesn't ++ for the second term for multiplication (and does ++ after multiplication)
i = 12

So the output = 121 12
Oct 14 '10 #2

100+
P: 687
There is no such thing as usual parameter passing sequence, it's not even implementation-defined and compiler is free to choose any order in any time.
Oct 14 '10 #3

Oralloy
Expert 100+
P: 983
What you have is an example of undefined behaviour.

The C/C++ specifications state that the compiler may evaluate an expression in any order.

Thus any expression which has multiple elements with side-effects makes no guarantee as to the result. Specifically, if there are multiple side effects on the same memory space, there is no guarantee of their application order.

Your expression in line 3 has side effects on the variable i twice, and uses the value of i three times. With no guarantee on execution order, what do you expect the result to be?

Also, as a side note, many compilers compute the arguments to functions/subroutines/methods in reverse order, so that they are pushed on the stack in correct order, and thus in ascending memory positions in the argument list. This, of course, assumes a stack which grows downward in memory.

Hopefully that helps.

Luck.
Oct 14 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.