Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good Form: Pointer vs. local variable vs. Array Index

Tags:

c

Forgive me if this comes across as a trivial question - I'm usually a control systems guy (plc's and automation) but have found myself involved in some embedded micro-controller and PC projects lately.

Let's say I have a function that accepts a pointer to an array of 'command bytes', typically 5 or 10 bytes in length, like so:

char cmd_i2c_read(unsigned char *cmd, unsigned short cmd_len) { ... }

I want to decode the command bytes (*cmd).

Is it better form to:

  1. Create local variables indicating the purpose of each byte:

    unsigned char device_address = cmd[2];
    unsigned char register_address = cmd[3];
    unsigned char num_bytes = cmd[4];
    // use the local variables: if(num_bytes &le 0xFF) { do_stuff(device_address, register_address, num_bytes); }
  2. Create local pointers:

    unsigned char *device_address = &cmd[2];
    unsigned char *register_address = &cmd[3];
    unsigned char *num_bytes = &cmd[4];
    // use the pointers: if(*num_bytes &le 0xFF) { do_stuff(*device_address, *register_address, *num_bytes); }
  3. Index the *cmd array directly:
    if(cmd[4] <= 0xFF) { do_stuff(cmd[2], cmd[3], cmd[4]); }

like image 567
user158485 Avatar asked Feb 23 '10 20:02

user158485


1 Answers

Option 1 is clear but a bit wordy. I don't like 2 at all, and 3 is hard to understand. Personally I prefer to use structs for this sort of thing.

typedef struct  {
   unsigned char whatever[2];
   unsigned char device_address;
   unsigned char register_address;
   unsigned char num_bytes;
   }  CMD;

CMD * pcmd = (CMD *)&cmd[0];

// use the local variables:
if(num_bytes ≤ 0xFF) {
    do_stuff(pcmd->device_address, pcmd->register_address, pcmd->num_bytes);
like image 136
John Knoeller Avatar answered Nov 13 '22 08:11

John Knoeller