Help me understand this cpp code

As of today I am not a cpp programmer , I have been programming in python from quite a long time now, I was implementing PMS 2.5 Dust Sensor when i came across belowcode on

// parsing state
typedef enum {
} EState;

typedef struct {
    EState  state;
    uint8_t buf[32];
    int     size;
    int     idx, len;
    uint16_t chk, sum;
} TState;

static TState state;

    Initializes the measurement data state machine.
void PmsInit(void)
    state.state = BEGIN1;
    state.size = sizeof(state.buf);
    state.idx = state.len = 0;
    state.chk = state.sum = 0;

I spent time trying to read the code and what I make out of above is that there are 2 data structure defined.
1 is of type enum and Second is of type struct

and then value of each Estate initalized object is set in PmsInit() function. Correct me if I am wrong !
in python the above will definitely not take these many lines.

enum is only an enumeration of different values (usually integer values) which get their own “names” to ensure that only certain values can be used and to make the code easier to read.
In your above example BEGIN1 equals to 0, BEGIN2 to 1, and so on. Whenever you create a variable/parameter of this type, only the values in the list are allowed.

The second is a struct which is a compound of multiple varaibles that can be treated as one new datatype where its individual fields can be accessed via the dot (e.g. state.size) or deref arrow (e.g. pointer2state->size) notation.

You may be right, but comparing C++ with Python is more than just by line count.
Like comparing a surgeons laperoscope to your bathroom tweezers :wink:

1 Like

I would have to develop a whole different way of thinking. I agree with you its not just lined of code…

Yup, a C/C++ programmers are usually a special breed of developers.
Just like not everybody can or wants to be a surgeon :wink:

1 Like