Sherifftwinkie
Sherifftwinkie

Reputation: 391

Using blocks in C

I have this code

#include <stdio.h>
#include <stdlib.h>

int main(){
int a = 5;
{
    int b = 6;
}
printf("%d %d", a, b);
return 0;
}

I am attempting to see how using a block would effect this but the program doesn't work. Says b is undeclared, this is the example I was given. Anyone know what is wrong? Or is it possible that this is suppose to throw me and error BECAUSE the int b is declared and initialized within the block when the printf isn't in there?

Upvotes: 2

Views: 237

Answers (1)

paxdiablo
paxdiablo

Reputation: 881563

Yes, b is undeclared where you try to print it. Its scope extends from its creation to the end of its block, which is the closing brace before the printf.

Perhaps you meant something like this:

#include <stdio.h>
#include <stdlib.h>

int main (void) {
    int a = 5;
    int b = 42;  // <<-- Look here! Yes, you! Right here! :-)
    {
        int b = 6;
        printf ("In block: %d %d\n", a, b);
    }
    printf ("Ex block: %d %d\n", a, b);
    return 0;
}

This has a b in scope at the point where you try to print it outside the block. It's not the b within the block but you'll find that out when the results are printed:

In block: 5 6
Ex block: 5 42

Upvotes: 8

Related Questions