do "if" structures define a scope?

I found an error in a program I downloaded, I can fix it but I don't understand it:

In the below code, the compiler yields the following error:

if_test.ino:7:13: error: 'hello' was not declared in this scope

byte ourbyte = 0;

void loop() {
  if(1){
    byte hello = 1;
    }
  ourbyte = hello;
  }

#2)
The original programmer seemed to like declaring variables in-line. I've always declare variables at the beginning of (the program, function etc). Is either considered poor form?

Thanks,

Google C++ Scope to learn about variables' scope.

Any section of code enclosed by braces comprises a scope. As you see here, the hello variable is not visible outside them.

Generally, it makes sense to have a variable declared in the most constrained scope possible. Information hiding means that only the code that needs to know about a variable can access it. It helps defend against bugs and makes it easier to find them when they do creep in because it restricts the area you need to examine. Globals mean you need to consider your entire codebase.

@wildbill,

Thank you,

For some reason I had it in my head that scope was related to loop and functions.

Your reasoning for limiting scope is appreciated.

Further thought; the code I posted is therefore useless! "hello" cannot be accessed after the if has completed.

John

Just to confuse:

byte hello = 1;
byte ourbyte = 0;

void loop()
{
    Serial.println(hello);
    Serial.println(ourbyte);
    if(1)
    {
        Serial.println(hello);
        Serial.println(ourbyte);
        byte hello = 2;
        Serial.println(hello);
        Serial.println(ourbyte);
        ourbyte = hello;
        Serial.println(ourbyte);
    }
    Serial.println(hello);
    Serial.println(ourbyte);
}

prints,
1
0
1
0
2
0
2
1
2

wildbill:
Any section of code enclosed by braces comprises a scope.

Literally.

The if is not necessary...

void loop( void )
{

  {
    int just_a_local = 1;

    {
      int just_a_local = 2;

      Serial.println(just_a_local);

      {
        int just_a_local = 3;

        Serial.println(just_a_local);
      }

    }

    Serial.println(just_a_local);
  }

}

And the brackets aren't necessary:

boolean just_a_local = false;


void setup() {
  Serial.begin(115200);
  
  if (just_a_local)
    int just_a_local = 2;  // warning: unused variable 'just_a_local'
  else
    int just_a_local = 3;  // warning: unused variable 'just_a_local'


  Serial.println(just_a_local);
}


void loop() {}