Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function passing arguments in reverse

Here is my function:

void abc(char  *def, unsigned int w, unsigned int x, unsigned int y, unsigned int z)
{
   printf("val 1 : %d\n", w);
   printf("val 2 : %d\n", x);
   printf("val 3 : %d\n", y);
   printf("val 4 : %d\n", z);
}

and here is where I call this function:

unsigned int exp[4] = { 1, 2, 3, 4 };
unsigned short count = 0;
abc(anyarray, exp[count++], exp[count++], exp[count++], exp[count++]);

and here is the output that I expect:

val1 : 1
val2 : 2
val3 : 3
val4 : 4

but what I get is completely reverse of it:

val1 : 4
val2 : 3
val3 : 2
val4 : 1

I don't know why? Any help would be appreciated.

like image 858
awatan Avatar asked Oct 02 '10 05:10

awatan


2 Answers

From standard docs, 5.4

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified58) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

An example from the Standard docs itself,

i = v[i ++]; / / the behavior is undefined

And it is for the very same reason that

abc(anyarray, exp[count++], exp[count++], exp[count++], exp[count++]); is undefined..

like image 177
liaK Avatar answered Oct 09 '22 05:10

liaK


You should not use the ++ operator, operating on the same variable, more than once in the same statement. The order in which the operation will be performed is not defined.

Try:

abc(anyarray, exp[count], exp[count+1], exp[count+2], exp[count+3]);  
count += 4; 
like image 45
Andrew Avatar answered Oct 09 '22 05:10

Andrew