0

(output printed is written in comment)
Just by giving int data type of the variable y which is within the paranthesis the output is different in program 2. How Memory allocation in stack segment will happen differently in both the cases.

Program 1

#include <stdio.h>

int main ()
{
    int y=10;
    {
        y=4; // this variable

        printf("%d\t",y);  //Output = 4 

    }  
    printf("%d",y);  //Output = 4  
}

Program 2

#include <stdio.h>

int main()
{
    int y=10;
    {
        int y=4;  // this variable

        printf("%d\t",y); // Output = 4
    }
    printf("%d",y);  // Output = 10 this output differ
}
1
  • If you could explain how shadowing with the same variable with int data type (int y) and without data type(y). What is the difference. Commented Aug 6, 2022 at 15:49

1 Answer 1

1
#include <stdio.h>

int main ()

{ // <--------- Scope 1 Begin

int y=10; >

{ // <--------- Scope 2 Begin

y=4;> this variable

printf("%d\t",y);>Output = 4 

} // <-------- Scope 2 End

printf("%d",y);>Output = 4  

} // <-------- Scope 1 End

In your first program here, you modify the y variable that you created in Scope 1. The second scope effectively does nothing here, as you still modify the original y from Scope 1. There is only one variable that was created here.

#include <stdio.h>

int main()

{ // <--------- Scope 1 Begin

int y=10;>

{ // <--------- Scope 2 Begin

int y=4;> > this variable

printf("%d\t",y); >Output = 4<

} // <-------- Scope 2 End

printf("%d",y); > Output = 10 this output differ <

} // <-------- Scope 1 End

However, in your program 2, by adding int before y=4 in Scope 2, you are instead initializing a new variable instead of assigning to y from Scope 1. This means that you are not modifying the y variable declared in Scope 1 when you do int y=4 from within Scope 2. As a result, the first y has the same value as when it was initialized. There are two variables that were created here.

As for memory usage, you can't really be sure without looking at the assembly output. It could be pushed and popped from the stack, or it could be optimized into a register, or it could even be removed altogether with a printf call with a literal.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.