Why array is not initialized inside if-statement?

Debojit Acharjee 435 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.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,853 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,602 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,625 questions
{count} votes

1 answer

Sort by: Most helpful
  1. YujianYao-MSFT 4,281 Reputation points Microsoft Vendor
    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.