Wednesday, June 08, 2011

Declaring multiple variables one line of code

Quiz time! Consider the following variable declaration in a C program:

float x, y = 0.0f;

What is the value of x?
















Answer: undetermined

This issue hit me, after so many years of ultra-explicit programming. A colleague way back in the UK taught me to prefer the explicit style of programming, since it's less likely to fall into traps like these. So coding programs in that style looks like:

char temp[ 512 ] = {"\0"};
int x = 0;
float y = 1.0f;

Everything gets initialized immediately after it is declared, so there is much less of a probability of picking up rogue / uninitialized values that way. This style also caused me to declare one variable per line.

I decided to take a shortcut after so many years for a quick experiment. Not just that... I decided to do this within a piece of embedded code running on a quadrotor.

The above shortcut led to the uninitialized value picking up the negative maximum value for an Arduino float: -2,147,483,648. Subsequently, this value was used in a calculation to add this particular value to an existing position. The result was a negative max float for latitude and longitude. This led to a quadrotor immediately hitting the limiter of the control system (-20 degree bank angle) and taking off to some undetermined location fractions after it was told to go into a position hold mode (where it stays in the same location in the xy plane at least).

After this line was changed to:

float x = 0.0f;
float y = 0.0f;

Things started working again. Since debugging on embedded systems is a huge pain in the *&(@#$, it took me some time to find and slap my head in disbelief.

This kind of thing is really easy to read over when you review code and definitely has the potential to have immense consequences... Another thing to seriously look out for.
( the assumption is that reviewers assume x = 0.0f as well, since it's part of the same line).

Proper code for multiple declarations in the same line look like this:

float x = 0.0f, y = 1.0f;

or:

float x = y = 0.0f;

1 comment:

Anonymous said...

Answer = Value of variable x was uninitialized.