Page 1 of 1

Reputation:

# Order of evaluation

Posted 25 October 2010 - 06:35 PM

```int f1(int *x) {
(*x)++;
return *x;
}

int f2(int *x) {
(*x) *= (*x);
return *x;
}

int main() {
int a = 2;
printf("%d\n",f2(&a) + f1(&a));
}

```

In standard left-to-right evaluation the result of this program is 9. This is because in f2 you set a to 2 and return 3. In f1 a returns 3 and you print 6.

In right-to-left evaluation f1 is evaluated first for a value of 3.

Am i getting this right? I do not know what the *= operator means in the f2.

Anybody push me in the right direction?
Thanks.

Is This A Good Question/Topic? 0

## Replies To: Order of evaluation

### #2 lfaivor21

Reputation: 10
• Posts: 29
• Joined: 17-October 10

## Re: Order of evaluation

Posted 25 October 2010 - 07:03 PM

I'm not sure exactly what you are asking for here but first things first.

```(*x) *= (*x);

```

is (in effect) equivalent to this statement

```(*x) = (*x) * (*x);

```

Basically it takes whatever is on the left side and multiplies it with whatever is on the right side then assigns (=) the result to (*x). Using the pointers allows direct manipulation of the memory itself in the function so in effect those two functions could be void and still a would be changed (Although you couldn't conveniently add the functions together like you did in your printf() statement). Passing values instead of addresses would look like so...

```int f1(int x){
return x++;
}

int main() {
int a = 2;
int b = f1(a);
return 0;
}

```

In this case if you decided to print a and b, a would still be 2 whereas b would be 3. In your case when you issue the statement...

```f2(&a)+f1(&a)

```

f2() changes the value that a is pointing at to 2*2 or 4 but it also returns that value (so f2(&a) has a value of 4) and f1() changes the value a points to yet again to 4+1=5 (so f1(&a) has a value of 5 in the statement). Now you add 4 and 5 and you get 9. If you print a after all this you'll notice it's value magically changed to 5 whereas if you'd passed it to the functions by value it would still be 2. So in summary you first pass a 2 to f2() and get 4... and then you pass a 4 to f1() and get 5. 4+5=9. Is this what you were looking for?

This post has been edited by lfaivor21: 25 October 2010 - 07:07 PM

### #3 aflamin24

Reputation: 0
• Posts: 17
• Joined: 05-November 08

## Re: Order of evaluation

Posted 25 October 2010 - 07:14 PM

### #4 Salem_c

• void main'ers are DOOMED

Reputation: 2143
• Posts: 4,208
• Joined: 30-May 10

## Re: Order of evaluation

Posted 25 October 2010 - 09:45 PM

We just did this sketch!
http://www.dreaminco...fferent-output/