Check if variable has been defined

4

How do I check if a variable has been defined?

Can #ifndef be used for this?

Being clearer:

#include <iostream>

int getNumber()
{
    if (check)
        {
            check = false;
            return 10;
        }
    else
        {
            bool check = true;
            return 20;
        }
}

int main()
{
    std::cout << getNumber() << endl;
    std::cout << getNumber() << endl;
    std::cout << getNumber() << endl;
}

I would like it to return:

20
10
20

But it returns the error:

|5|error: 'check' was not declared in this scope|

The variable can not be defined in the main() function, since the getNumber() function will be called elsewhere as well.

    
asked by anonymous 03.01.2015 / 01:32

2 answers

7

Unfortunately the question has been changed and you are now asking something completely different from the original, I will leave the original answer below

Even understand that you are learning but what you want to do requires state and can not do so trivial. Guilherme Nascimento's response code works, if you run only this isolated example. If it will be used within a more complex application, you will have problems.

You will have to save the situation in some variable and this variable will have to be known by its function in isolation. If you use a global variable you'll have problems (see more here , here and here ).

You can create a class or at least one structure to do this but in fact as it is something that does not quite fit a new data structure does not need so much, can do something simpler, something like this:

#include <iostream>

int getNumber(bool &check) { //recebe o estado por referência
    if (check) {
        check = false;
        return 10;
    } else {
        check = true;
        return 20;
    }
}

int main() {
    bool numero = false;
    std::cout << getNumber(numero) << endl;
    std::cout << getNumber(numero) << endl;
    std::cout << getNumber(numero) << endl;
}

See running on ideone .

I know you will find it more complicated. But what's the use of something simple and wrong? This way you can have as many states as you want. If you do not do this or the function happens to have very little utility or you will have to coordinate the use of it, which is much harder than doing this.

I used the parameter by reference so any change in the variable check within the function also changes the variable that sent the value to the function, so the variable numero is always in the proper state for that moment.

If you checked to see if a variable was created or not, its logic would not work unless you had the variable erased, which does not make sense. The very title of your question does not make sense with the actual current question.

Please note that I have not improved your code.

A more sophisticated example running on ideone . I do not recommend using the third form since it uses a static variable, that is, global state. But at least it's encapsulated in one function, it helps.

C ++ is a compiled and static typing language. All variables must exist at compile time. Contrary to what you are accustomed to with dynamic languages, you can not treat variables as data directly.

Remember of this question ? There is a hint to simulate the dynamic variables. In the background dynamic languages make more or less that map that I indicated for you. When you are programming you have the illusion that you are using variables but in the background you are accessing positions in these maps also called dictionaries or hashes .

You see why these variables are dynamic and may or may not exist? Because they are given in key-value pairs, where the key is the name of the variable and the value is what is stored in that "variable".

Even some dynamic languages can have real variables. In general, local variables are considered real. These variables must always exist. These variables are preferable because they are more secured by the compiler and are faster.

If you really have a problem that the variable may or may not exist, use a map and simulate the variable. In C ++ it does not have syntax that facilitates access as if it were a truthful variable.

But you can probably do the same thing differently. When programming in static languages you have to think in a different way.

Guilherme Nascimento's answer is correct, but these variables he is talking about only exist in the compilation process, they have no use in the application itself. They are used to help compile the application and not to run it. And its use is discouraged whenever possible (it is not always). Think of two different languages that are in the same code but do not communicate. Preprocessor variables are not even part of C ++.

If you still think you need this, ask a question saying where you want to go, maybe we have a better solution.

    
03.01.2015 / 02:12
4

Variables in C / C ++ can not be used if they are not defined, because the compiler will issue an error message and your project will not be compiled, in other words, there is no way to check if the variable was defined, because there is no need.

Depending on your example, you just need to set the variable before the function and remove the bool that is in else . Note that bool check is out of main() so you can access elsewhere (as you mentioned in your "PS."):

#include <iostream>

bool check;

int getNumber()
{
    if (check) {
        check = false;
        return 10;
    } else {
        check = true;
        return 20;
    }
}

int main()
{
    std::cout << getNumber() << std::endl;
    std::cout << getNumber() << std::endl;
    std::cout << getNumber() << std::endl;
}

You can also create a class, which would help to leave the variable "isolated".

But as you posted the code #ifndef is used to check if the MACRO has been defined ( this is not a variable ) and as Maniero quoted, this is only used at compile time, so does not have the same purpose as the variables.

Read on at: link

There are several advantages to using MACROS, one is why it is mandatory to use headers ( .h or .hpp ), to prevent failures if it is inserted more than once. >

We can also use it to create two events or operations for each type of compiler:

#ifdef __MINGW32__
void MainWindow::test ()
{
   //trabalhar com MingW
}
#else
void MainWindow::test ()
{
   //Outro compilador
}
#endif

You can quickly define in a global file a MACRO to say whether the application is production (being used by "people") or development (you are doing maintenance or creating it).

So MACRO is different from variable (since macro usually has no variation in its data).

    
03.01.2015 / 01:47