C Operator Precedence with pointer increments

纵饮孤独 提交于 2020-01-17 03:59:51

问题


I am trying to understand a line of C-code which includes using a pointer to struct value (which is a pointer to something as well).

Example C-code:

// Given
typedef struct {
    uint8 *output
    uint32 bottom
} myType;
myType *e; 

// Then at some point:
*e->output++ = (uint8) (e->bottom >> 24);

Source: http://tools.ietf.org/html/rfc6386#page-22

My question is:

  • What exactly does that line of C-code do?

回答1:


"What exactly does that line of C-code do?"

Waste a lot of time having to carefully read it instead just knowing at a glance. If I was doing code review of that, I'd throw it back to the author and say break it up into two lines.

The two things it does is save something at e->output, then advance e->output to the next byte. I think if you need to describe code with two pieces though, it should be on two lines with two separate statements.




回答2:


As pointed out by Deduplicator in the comments above, looking at an operator precedence table might help.

  • *e->output++ = ... means "assign value ... to the location e->output is pointing to, and let e->output point to a new location 8 bits further afterwards (because output is of type uint8).
  • (uint8) (e->bottom >> 24) is then evaluated to get a value for ...



回答3:


The line

*e->output++ = (uint8) (e->bottom >> 24);

does the following:

  1. Find the field bottom of the structure pointed to by the pointer e.
  2. Fetch the 32-bit value from that field.
  3. Shift that value right 24 bits.
  4. Re-interpret that value as a uint8_t, which now contains the high order byte.
  5. Find the field output of the structure. It's a pointer to uint8_t.
  6. Store the uint8_t we computed earlier into the address pointed to by output.
  7. And finally, add 1 to output, causing it to point to the next uint8_t.

The order of some of those things might be rearranged a bit as long as the result behaves as if they had been done in that order. Operator precedence is a completely separate question from order in which operations are performed, and not really relevant here.



来源:https://stackoverflow.com/questions/27281887/c-operator-precedence-with-pointer-increments

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