Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator Precedence in C - Returning a Value

I have this statement:

return *local_stack_var2++ + 42;

Would these be the proper steps when breaking it down:
1. Dereference local_stack_var2
2. Add 42 to the dereferenced local_stack_var2 (function will actually return this value)
3. Before the function is over, it will activate the post-increment, incrementing the value of the object pointed to by local_stack_var2

So in code format, it would look kind of something like this?

int temp = *local_stack_var2 //step 1;  
int returnValue = temp + 42; //step 2, compiler will return THIS value     
*local_stack_var2 = *local_stack_var2 + 1; //step 3 
 return returnValue;

Thanks!

like image 274
lordmarinara Avatar asked Dec 05 '11 00:12

lordmarinara


1 Answers

Close, but ++ (postincrement) has higher precedence than unary *, so it happens first. The order of operations would be:

  1. Post increment local_stack_var2 so that it is incremented by one but the expression evaluates to the original value, not the incremented value
  2. Dereference that original value
  3. add 42 to what was obtained by dereferencing the aforementioned original value
  4. return that value

So in code, it would be like (not precisely, but close)

int* temp = local_stack_var2;
local_stack_var2 = local_stack_var2 + 1;
int retval = *temp;
reval = retval + 42;
return retval;
like image 143
Seth Carnegie Avatar answered Oct 15 '22 23:10

Seth Carnegie