Initialization of automatic variables in C

I recently participated in a code inspection for my colleague, Prakash. He was fixing a bug caused by a jump into a block of code that resulted in an automatic variable failing to be initialized. Let me show you:

goto fragmented;
if (u1) {
boolean_t     pruned=B_FALSE;
if (pruned && offset != 0) {

So, in the above code the variable “pruned” is not being initialized. It seemed to me that
it would either be illegal to jump in like this at all, or that it would “just work” and that
the initialization would be done. Prakash thought so too but was able to fix the problem
pragmatically by adding the line “pruned = B_FALSE;” just after the label.

I was curious, so I went to the ISO C standard and looked it up. The language used is a
bit vague, but apparently storage for automatic variables must be allocated upon entry to a
block by any means (meaning that the goto is legal) but that initialization of that storage
only occurs when the execution passed over the lines of code that declare the variable. This guarantees that the variables are initialized in a deterministic order, but in this case it means that pruned isn’t initialized at all, since execution jumps to just after it is

I know you probably already knew this, but it was news to Prakash and me. Well, live and learn.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: