How to define nested block for temporary local variables in C

1 Answer

0 votes
#include <stdio.h>
  
int main(void)
{
    short n = 40;
  
    if (n > 10)
    {
        n = n * 2;
         
        int k = 60; // block variable
        k += n;
        printf("k = %d\n", k);  // (40 * 2) + 60 = 140
    }
    //printf("k = %d\n", k); // error! k undeclared outside of block if above
     
    n = n / 2;
    { 
        /* we can define nested block (inside main() function in this example) 
           when we need him without if or loops */
            
        //printf("k = %d\n", k); // error! k undeclared yet in this block
          
        int l = 20, k = 60; // block variables, k is not the same k as in if block above
        k += n + l;
        printf("k = %d\n", k); // 60 + (80 / 2) + 20 = 120
    }
    //printf("k = %d\n", k); // error! k undeclared outside of block if above 
     
    return 0;
}


/*
run:

k = 140
k = 120

*/


answered Aug 15, 2014 by avibootz
edited Jan 5 by avibootz

Related questions

1 answer 222 views
2 answers 255 views
2 answers 176 views
1 answer 259 views
1 answer 337 views
1 answer 220 views
220 views asked Oct 7, 2014 by avibootz
...