Thought Leadership

Variable declarations in C – plenty of pitfalls

By Colin Walls

It is widely felt that C is a very good language for embedded applications, as it is expressive, compact and powerful. It is possible to write very clear, readable code, but that takes care. Even the simplest things, like the declaration of variables, have pitfalls for the unwary …

In C, you can declare variables in one of two places: the head of a block or outside of function code. In either case, the syntax is the same:

[ <qualifier> ] <type> <identifier> [, <identifier>] ;

For example:

float x, y, z;

Many developers feel that it is bad practice to declare for than one variable on each line. For example:

int temperature, time_delay;   // user selected parameters

is not such a good idea, as it might be written more clearly thus:

int temperature;   // user selected temperature
int time_delay;    // user selected interval

It may be acceptable to declare multiple variables on one line, if they are closely bound together. For example:

static float x, y, z; // spacial coordinates

However, it might be argued that this is a case when a data structure – struct or class – might be better.

A further complication is that a declaration can contain variables of different types – base types and pointers, thus:

int n, *p, **p2p;

This is clear enough – we have an int, a pointer to int and a pointer to a pointer to int. But there is still the commenting issue.

Matters are made worse if we write a declaration like this:

int* p;

This is favored in the C++ world and is arguably clearer – the type is pointer to int. However, this code:

int* p1, p2;

is misleading. Although p1 is a pointer to int, p2 is just a plain int.

So, what is the answer? Multiple variables on the line or not? In my view, a single variable per line should be the default, reserving multiple declarations for special cases. If you have views on this matter, I would welcome a comment, email or contact via social media.

Leave a Reply

This article first appeared on the Siemens Digital Industries Software blog at https://blogs.sw.siemens.com/embedded-software/2016/08/08/variable-declarations-in-c-plenty-of-pitfalls/