Scope of variables in if statements

declare variable in if statement c++
create variable in if statement python
if statement scope javascript
declare variable in if statement c#
c declare variable in if statement
php variable scope if statement
c++ if statement
change variable in if statement python

I have a class that has no default constructor or assignment operator so it is declared and initialized within an if/else statement depending on the result of another function. But then it says that it is out of scope later even though both routes of the conditional will create an instance.

Consider the following example (done with int just to illustrate the point):

#include <iostream>

int main() 
{
  if(1) {
    int i = 5;
  } else {
    int i = 0;
  }

  std::cout << i << std::endl;
  return 0;
}

Do variables declared in a conditional go out of scope at the end of the conditional? What is the correct way to handle the situation where there is no default constructor but the arguments for the constructor depend on certain conditionals?

Edit

In light of the answers given, the situation is more complex so maybe the approach would have to change. There is an abstract base class A and two classes B and C that derive from A. How would something like this:

if(condition) {
   B obj(args);
} else {
   C obj(args);
}

change the approach? Since A is abstract, I couldn't just declare A* obj and create the appropriate type with new.

"Do variables declared in a conditional go out of scope at the end of the conditional?"

Yes - the scope of a local variable only falls within enclosing brackets:

{
   int x; //scope begins

   //...
}//scope ends
//x is not available here

In your case, say you have class A.

If you're not dealing with pointers:

A a( condition ? 1 : 2 );

or if you're using a different constructor prototype:

A a = condition ? A(1) : A(2,3);

If you're creating the instance on the heap:

A* instance = NULL;
if ( condition )
{
   instance = new A(1);
}
else
{
   instance = new A(2);
}

or you could use the ternary operator:

//if condition is true, call A(1), otherwise A(2)
A* instance = new A( condition ? 1 : 2 );

EDIT:

Yes you could:

A* x = NULL; //pointer to abstract class - it works
if ( condition )
   x = new B();
else
   x = new C();

EDIT:

It seems what you're looking for is the factory pattern (look it up):

 class A; //abstract
 class B : public A;
 class C : public A;

 class AFactory
 {
 public:
    A* create(int x)
    {
       if ( x == 0 )
          return new B;
       if ( x == 1 )
          return new C;
       return NULL;
    }
 };

Scope of variables in if statements, "Do variables declared in a conditional go out of scope at the end of the conditional?" Yes - the scope of a local variable only falls within  If the value is true, then the contained Statement is executed; the if-then statement completes normally if and only if execution of the Statement completes normally. If the value is false, no further action is taken and the if-then statement completes normally. However, JLS-14.5. Statements doesn't include variable declaration.

Do variables declared in a conditional go out of scope at the end of the conditional?

Yes.

What is the correct way to handle the situation where there is no default constructor but the arguments for the constructor depend on certain conditionals?

Write a function that returns a value, from which you copy.

T foo()
{
    if(condition)
        return T(x);
    return T(y);
}

void bar()
{
    T i(foo());
}

Edit:

Since A is abstract, I couldn't just declare A* obj and create the appropriate type with new.

What do you mean? That's exactly how dynamic typing works. Except I wouldn't use a raw pointer, I would use a unique_ptr.

std::unique_ptr<A> obj;
if(condition) {
   obj = std::unique_ptr<A>(new B(args));
} else {
   obj = std::unique_ptr<A>(new C(args));
}

If Statement Variable Scope In PHP, If statements do not have their own variable scope. To better understand what all this means, here are a couple examples. In this example we  Alright I seem to have a misconception with variable scope with PHP, forgive my lack of the subject as I come from a Java, C# background. Thinking I could make variables accessible to functions or if statements simply by placing it outside it. Below is a snippet of what I'm trying to accomplish:

Yes it will be out of scope if declared in a conditional, loop etc. Will the type of the variable change depending on the conditional?

if statement, If the else part of the if statement is present and condition yields false after (if condition is a declaration) are in the same scope, which is also the scope of The discarded statement can odr-use a variable that is not defined. If Statement Variable Scope In PHP. Variable scope is the context within your code in which a variable is defined and able to accessed. If you try to access a variable that is out of scope, the variable will be undefined and you will not get the results you are expecting.

Your alternative will be pointers:

MyObject *obj;
if(cond1)
{
    obj = new MyObject(1, 2, 3);
}
else
{
    obj = new MyObject(4, 5);
}

Remember to delete it when you are done with it, or use a smart pointer.

var, The scope of a variable declared with var is its current execution The value will be indeed assigned when the assignment statement is  variable 'a' can be accessed in any if statement as its declare outside the block but, variable 'b' is declare inside if hence limited its use outside the block. If you want to use 'b' outside the if statement you have to declare it where you have declare variable 'a'.

Why can't I declare variables inside an if statement?, Declaring a variable inside a block means that they only exist within that block. Once the block is exited, they become inaccessible. To understand the scope of variables, it is important to first learn about what variables really are. Essentially, they're references, or pointers, to an object in memory. When you assign a variable with = to an instance, you're binding (or mapping) the variable to that instance. Multiple variables can be bound to the same instance.

Programming via Java: Conditional execution, Variable scope. Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available  Scope of variables in if statements. I have a class that has no default constructor or assignment operator so it is declared and initialized within an if/else statement depending on the result of another function. But then it says that it is out of scope later even though both routes of the conditional will create an instance.

c# – Declare variables outside if-else statement scope – CodingBee, c# – Declare variables outside if-else statement scope. If you declare (and initialize) a variable within an if-else statement, then that variable's value will only​  The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.

Comments
  • Is your inheritance virtual or static?
  • Virtual, I think. class A has a virtual function, if that's what you mean (C++ isn't my strong suit, I work mostly in Fortran)
  • You actually can declare a pointer to an abstract class - I edited my answer.
  • Is the memory reallocated in this case ?? After the variable scope ends after the enclosing { } brackets.
  • This answer contradicts the first answer? (about whether variables declared in a conditional will go out of scope at the conditional's end)
  • @Gnuey: No it doesn't. I'm not sure exactly which question Luchian is answering "No" to. Perhaps he just got the verbiage confused between the time he read the question and the time he wrote the answer. But the full statement, as well as the commented code snippet that follows it, clearly agree with my answer.
  • So there are both cases. Sometimes it is the same type regardless of the conditional, sometimes it is a different type depending on the conditional. How would the approaches change for the two situations?
  • I have. I see how it addresses the first case (same type). How does it address the possibility of different types being declared based on the conditional?