Why array is not initialized inside if-statement?

Debojit Acharjee 455 Reputation points
2023-05-27T05:15:17.8233333+00:00

I want to know why the text is not initialized to the array in the program below.

#include <stdio.h>

char a[] = "RED";

int main ()
{

int b=-1, c=0;

printf("Enter number: ");
//scanf("%d", b);

if (b < 0)
{

char a[] = "GREEN";
c = 1;

}

char a[] = "BLUE";

    printf("%d, %s", c, a);

    return 0;
}

In this program the if stamen is fired by the variable 'b', but why the array 'a' is not assigned the text "GREEN"? The output shows only the value of c.

Developer technologies C++
Developer technologies Visual Studio Other
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. YujianYao-MSFT 4,296 Reputation points Microsoft External Staff
    2023-05-29T06:39:41.8566667+00:00

    Hi Debojit Acharjee,

    In your code, a is a global variable that is initialized to "RED" at the beginning of the program. And in the main function, you declare a local variable a and assign it the value "GREEN". However, when you refer to the variable a in the printf statement, it still refers to the global variable a.

    This is because in C language, local variables override global variables of the same name. The local variable a declared in the if statement block will shadow the scope of the global variable a, but it is only valid inside the if statement block. When you refer to a in the printf statement, it refers to the global variable a, not the local variable. And c is not redefined, it is still previously defined, so its value will change.

    If you set a breakpoint, we could see that the value of a in the if block will become "GREEN", and the value of a will no longer be "GREEN" when the if block is run out.

    User's image

    Best regards,

    Elya Yao


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.