0

If I run following code, I get output

From inside innermost braces c is 5

from just outside innermost brace, c is 8

from inside function 48

From just before end of main c is 8

But if I change first line in if block to c = a + b; from int c = a + b;

I get output

From inside innermost braces c is 5

From just outside innermost brace, c is 5

from inside function 30

From just before end of main c is 5

My question is what determines penetrance of local variable in and out of the block?

#include <stdio.h>


void multiply (int a, int b, int c);
main ()

{
  int a = 2, b = 3,  c = 8;

if (a == 2)
    {
        int c = a + b;// if I make this statement as c = a+b,then next both printf will be both 5
        printf ("\nFrom inside innermost braces c is %d\n",c);
    }
printf("\nFrom just outside innermost brace, c is %d\n", c);
multiply (a,b,c);
printf ("\nFrom just before end of main c is %d\n",c);
}



void multiply (int a, int b, int c)                       

{
  printf ("\nfrom inside function  %d\n", a*b*c);
}

1 Answer 1

2

Variables are declared in block-scope, available in the current and any of its inner blocks. Variables "shadow" outer ones of the same name.

Function parameters work like variables declared for the whole function. By default they hold a copy of the value passed to the function (so main's a,b,c are different from multiply's a,b,c even if they have same values)

When you access variable c, it is searched for in current block-scope. If there's no c in this block, the next outer block is searched. If there's still no c when reaching the current function's scope, global scope is searched instead.

Note that a function's scope does not include the calling function's scope.

2
  • Why does c value change when I changed first line in if block to c = a + b; from int c = a + b? Thanks
    – rasdocus
    Commented Apr 12, 2017 at 13:08
  • In first case you change the outer variable c, with the int you declare a new variable instead, shadowing the outer one.
    – Blauelf
    Commented Apr 12, 2017 at 13:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .