Help Understanding Scope article || C

I’m new to coding, and chose to start off with C. As I’m going through the article on scopes I came across a multiple-choice question which the answer makes no sense to me and seems to be a fairly simple concept.

The question reads:
“Given the following code block, how many names are locally available in the myFunc() and main() scopes?”

The code is as follows:

void myFunc() {
int a = 100;
int b = 1000;
if (a > b) {
int c = 10;
} else {
int c = 5;
}
}

int main() {
int x = 100;
int a = 200;
char* name = “Bob”;
if (x == a) {
int z = 30;
printf(“Hello”);
}
}

How are there not 3 names in Myfunc()? Obviously int a and b are names within Myfunc(), but why is int c not considered a name in this scope? I figured it was because it was in the if scope, but if we look at main(), all 3 variables are considered to be names in the main() scope, even int z, which is in the if scope.

Any advice is helpful, thank you

You are correct that in myFunc, the variable c is in the scope of the if block.

In main, z is in the if scope. The integer variables x and a are in the scope of main. The third variable in the scope of main is name. (It is a pointer to a string. Basically, it points to the first character of the string. Since “Bob” is a string literal, so the null character '\0' is implicitly added at the end). So, the third variable in the scope of main is name not z.

Try the following modifications (if you don’t have C installed, search for ‘C online compiler’ and you will get plenty of options):

#include <stdio.h>

void myFunc() {
    int a = 100;
    int b = 1000;
    if (a > b) {
        int c = 10;
    } else {
        int c = 5;
    }
    printf("%d\n", a);
    printf("%d\n", b);
    // printf("%d\n", c);  <--- Uncommenting this will cause error
}

int main() {
    myFunc();    // <-- Added function call
    int x = 100;
    int a = 200;
    char* name = "Bob";
    if (x == a) {
        int z = 30;
        printf("Hello");
    }
    printf("%d\n", x);
    printf("%d\n", a);
    // printf("%d\n", z);  <--- Uncommenting this will cause error
    printf("%s\n", name);
}

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.