Open side-bar Menu
 Embedded Software
Colin Walls
Colin Walls
Colin Walls has over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, Colin is an embedded software technologist with Mentor … More »

Variable declarations in C – plenty of pitfalls

 
February 15th, 2021 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 of p 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.

Logged in as . Log out »




© 2024 Internet Business Systems, Inc.
670 Aberdeen Way, Milpitas, CA 95035
+1 (408) 882-6554 — Contact Us, or visit our other sites:
TechJobsCafe - Technical Jobs and Resumes EDACafe - Electronic Design Automation GISCafe - Geographical Information Services  MCADCafe - Mechanical Design and Engineering ShareCG - Share Computer Graphic (CG) Animation, 3D Art and 3D Models
  Privacy PolicyAdvertise