-2

I am learning c++ and I came across a really odd phenomenon in a program. I haven't seen any documentation on this problem. Why is that when I initialize a variable inside of a conditional statement it isn't recognized outside of it? Is the variable local to the conditional statement?

Here is an example:

#include "stdafx.h"
#include <iostream>

using namespace std;
/*scope / range of variables */


int global;

int main()
{
   int local = rand();

   cout << "value of global " << global << endl;
   cout << "value of local " << local << endl;

   int test = 10;

   if (test == 0)
   {
      int result = test * 10;
   }

   cout << "result :" << result << endl;

    return 0;
}

In this case result is undefined. Can someone please explain what is going on?

Evan Gertis
  • 1,796
  • 2
  • 25
  • 59

1 Answers1

1

As pointed out in the comments, your declaration of result is local inside the if() blocks scope you provided:

if (test == 0)
{ // Defines visibility of any declarations made inside
  int result = test * 10;
} //  ^^^^^^

Hence the statement

cout << "result :" << result << endl;

would lead to a compiler error, since result isn't visible for the compiler at this point outside that scope.


But even if you declare result correctly outside of the scope block, your logic

int result = 0; // Presumed for correctness
int test = 10;

if (test == 0)
{
    result = test * 10; // Note the removed declaration
}

doesn't make much sense, since test was given the value 10 immediately before testing it against the value 0 in your your if() statements condition, and the condition never would become true.