Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,705 questions

55,464 answers

573 users

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 248 views
2 answers 281 views
2 answers 205 views
1 answer 286 views
1 answer 359 views
1 answer 238 views
238 views asked Oct 7, 2014 by avibootz
...