SuperUser_Novice SuperUser_Novice - 4 years ago 285
C++ Question

Error: Variable Not declared in this scope

In the main file for testing I started with code similar to this.

//Initialize the data type for the vectors and input variables
if ( choice == 1 )
{
vector<int>MyVector{};
vector<int>NewVect{};
int k1{}, k2{};
}

else if ( choice == 2 )
{
vector<float>MyVector{};
vector<float>NewVect{};
float k1{}, k2{};
}
//Exact Same block for double
while ( true )
{
cout<<": ";
cin>>k1>>k2;
if ((k1 == 0 ) && (k2 == 0)) break;
else
{
MyVector.push_back(k1);
MyVector.push_back(k2);
continue;
}
}
//Insert Sort Algorithm test, Imported from class InsertSort.
//NewVector = sort.sort(MyVector)
return 0;
}


It continues like this into two other else if statements declaring float and double respectively ( using the same variable names ). The compilation however stops and says that k1, k2, MyVector, and NewVector were not declared in this scope further into the program. I declared it within the "global" portion of main so I'm not really understanding why the declaration isn't happening. Is it not possible to try to declare the same variable of a different type within if/else if statements?

I'm trying to do it this way to avoid additional tests within the input loop, that way there is one check for the data type, the proper data types are defined and the code will be shorter than it would have been. Any ideas what's happening?

EDIT: Code Added.

Answer Source

You cannot declare a variable which's type depends on a run-time condition. Types of variables are declared/specified at compile time. Knowing that, you tried to declare different types inside the if blocs, but then, the scope of each variable is limited to the bloc in which it is declared.

What you are trying can be achieved using some kind of polymorphic variable, or variable of any type, which will be available in C++17 but not before, under the name of std::any. In the mean time, you can try to make for yourself something similar using unions. The following can provide a starting example to making your own any type, the example defines an any that holds either an int or a double:

#include <iostream>
#include <vector>

struct any {
  union { int intVal = 0; double dblVal;};
  enum {Int = 1, Dbl = 2} type = Int;

  any(int val) : intVal(val) {type = Int;}
  any(double val) : dblVal(val) {type = Dbl;}
  any() {}
};

std::ostream& operator <<(std::ostream& os, const any& x) {
    switch(x.type) {
        case any::Int : os << x.intVal; break;
        case any::Dbl : os << x.dblVal; break;
    }
    return os;
}
int main()
{
    std::vector<any> vect;
    any k1, k2;

    vect.emplace_back(3);
    vect.emplace_back(4);
    vect.emplace_back(9.5);
    vect.emplace_back(10.5);

    for (const auto& i: vect)
        std::cout << i << "  ";
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download