Home > Learning > C blocks and variable declaration

C blocks and variable declaration

First thing I learned in the “I’m supposed to know this already!” class (Advanced C++ Programming) is actually about C.

In C++ variables can be declared anywhere in the scope of a function (well, anywhere before they’re used). In C, however, they have to be declared at the beginning of the function. Or so I thought. It’s actually at the top of the block. And a block is delimited by curly braces.

In other words, declaring at the top of a function:

void MyFunction(void)
{
    int myVar;
    //...
}

Inside a control structure:

void MyFunction(void)
{
    if(/*some condition*/)
    {
        int myVar;
        //...
    }
}

or

void MyFunction(void)
{
    for(/*start, end, iteration*/)
    {
        int myVar;
        //...
    }
}

or even

void MyFunction(void)
{
    switch (/*expression*/)
    {
        case 1:
        {
            int myVar;
            //...
        }
    }
}

And even just out of the blue:

void MyFunction(void)
{
    //some code
    {
        int myVar;
        //...
    }
}

Although this last form should arguably be used sparingly. And here I thought I had to list it all at the very beginning of the function. I’m ashamed, but I’m glad I know now.

Add-on: I forgot to mention the scope. The variable exists in the block. It’s a local declaration only valid in it. Outside the block, the variable no longer exists. Your compiler will tell you if you refer to a variable declared in a block outside of it.

Advertisements
Categories: Learning Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: