Operator Precedence in C - Returning a Value

谁都会走 提交于 2021-01-27 05:19:33

问题


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!


回答1:


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;


来源:https://stackoverflow.com/questions/8379810/operator-precedence-in-c-returning-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!