Reputation: 1369
Here is a recursive code using side effects in function argument.In K&R, i found a statement saying C standard specifies that all side effects on arguments take effect before a function is called(page no.54 K&R second edition).But output to above code was contradictory.Could anyone help me out.
void reverse(int* array,int i,int j)
{
`int temp;
if(i>j)
return ;
else{
temp=array[i];
array[i]=array[j];
array[j]=temp;
//i++;
//j--;
reverse(array,i++,j--);
}
} '
PS:Output is segmentation fault
Upvotes: 0
Views: 811
Reputation: 2742
It's true that the variables get incremented before the function call, but those variables are local to the function in which they're declared (in this case, one recursive function call frame), and when you use the postfix operators, the value returned by the operators is not the updated value but rather the initial value. Consequently, the values that you end up passing as parameters are not properly updated and your function will never terminate. In order to increment the variables and simultaneously return and pass-in the updated values, you have to use prefix operators, i.e., ++i
and ++j
.
Upvotes: 3
Reputation: 3678
all side effects are completed, so the value of i and j is changed before function call.
but the value of express i++
and j--
are still the value of i and j previously.
Upvotes: 2