Etienne Bruines
Etienne Bruines

Reputation: 3038

C Operator Precedence with pointer increments

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: https://www.rfc-editor.org/rfc/rfc6386#page-22

My question is:

Upvotes: 0

Views: 101

Answers (3)

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

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.

Upvotes: 1

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25605

"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.

Upvotes: 3

Etienne Bruines
Etienne Bruines

Reputation: 3038

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 ...

Upvotes: 1

Related Questions