Pitfalls in C: Declaring Variables

October 23, 2020 Colin Walls, Mentor

C is the most commonly used language for embedded, with good reason. It is expressive, compact and powerful. With care, it is possible to write very clear, readable code. But there are pitfalls along the way, which can be the simplest of constructs, like the declaration of variables.

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;

It is often felt that it is bad practice to declare for more than one variable on each line. For example:

int temperature, time_delay;   // user selected parameters

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 – a struct - 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. And 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. Other views are available.

Previous Article
Improving Semiconductor Manufacturing Through Smart Technologies
Improving Semiconductor Manufacturing Through Smart Technologies

Internet of things (IoT) devices have become the largest driver of semiconductor revenue, with wireless com...

Next Article
How Voice Codecs Are Adapting to MEMS Microphones
How Voice Codecs Are Adapting to MEMS Microphones

As voice interfaces and digital assistants become more popular, there will be a growing need for compact, a...