What is the difference between scope and block?

后端 未结 9 1165
旧巷少年郎
旧巷少年郎 2021-01-04 05:16

I saw a piece of code in a book, which is as follows:

x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}

9条回答
  •  暖寄归人
    2021-01-04 06:06

    when it comes to conditions and loops if you don't specify {} then immediate following statement is the only statement that will belong to particular condition or loop

    e.g.

    x = 10;
    if(x ==10) 
    { 
    int y = 20; 
    x = y * 2;
    }
    both lines get executes only if condition returns TRUE
    
    x = 10;
    if(x ==10) 
    int y = 20;
    x = y * 2; // this is not belong to if condition. therefore it will execute anyway
    

提交回复
热议问题