Check if variable has been set

Asked

Viewed 887 times

5

How do I check if a variable has been set?

The #ifndef can be used for this?

Plainer:

#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’d like you to return:

20
10
20

But returns the error:

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

Variable cannot be defined in function main(), for the function getNumber() will be called in other places too.

  • 2

    I’ve told you not to change the question you asked before. And to put examples, detail what you want from the beginning. You may be thinking it’s the same question. But when you put what you want to do, you changed the question completely. The answers given before no longer serve because you originally asked one thing and you wanted to know something else.

2 answers

8


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

I understand that you are learning but what you want to do requires state and can not do so trivial. William Nascimento’s response code works if you just run this isolated example. If you are going to use within a more complex application, you will have problems.

You will have to store 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 will have problems (see more here, here and here).

You can create a class or at least a structure to do this but actually as it is not enough to assemble a new data structure not need so much, can do something simpler, something like that:

#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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I know you’ll find it more complicated. But what good is something simple and wrong? This way you can have as many states as you want. If you don’t do so or the function becomes extremely useful or you will have to coordinate the use of it, which is much more difficult 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, then the variable numero is always in the right state for that moment.

If you could verify whether a variable was created or not, its logic would not work unless you had the variable deleted, which makes no sense. The very title of your question makes no sense with the actual current question.

Note that on ideone I improved your code.

I made a more sophisticated example. I do not recommend using the third form since it uses a static variable, ie global state. But at least it’s encapsulated in a function, it already helps.

#include <iostream>
using namespace std;
template <typename T>
class Interleave {
    T a, b;
    bool check = false;
    public:
        Interleave(T a, T b) {
            this->a = a;
            this->b = b;
        }
    
        T getValue() {
            check = !check;
            return check ? a : b;
        }
};

int getNumber() {
    static Interleave<int> numero(10, 20);
    return numero.getValue();
}

int main() {
    Interleave<int> numero(10, 20);
    cout << numero.getValue() << endl;
    cout << numero.getValue() << endl;
    cout << numero.getValue() << endl;

    Interleave<string> texto("aaa", "bbb");
    cout << texto.getValue() << endl;
    cout << texto.getValue() << endl;
    cout << texto.getValue() << endl;

    cout << getNumber() << endl;
    cout << getNumber() << endl;
    cout << getNumber() << endl;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.


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

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

Have you noticed why these variables are dynamic and may or may not exist? Because they are given in key pairs value, where the key is the variable name and the value is what is stored in this "variable".

Even some dynamic languages may have real variables. In general local variables are considered real. These variables must also always exist. These variables are preferable because they are more guaranteed 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++ there is no syntax that facilitates access as if it were a truth variable.

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

Guilherme Nascimento’s answer is correct, but these variables that 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, not to run it. And their use is discouraged whenever possible (not always). Think of two different languages that are in the same code but do not communicate. Preprocessor variable are 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.

  • Thank you for commenting, I would like to make it clear that I answered exactly as the author asked, he needed access to the variable OUT of "main" so so it was not a matter of example that I provided, but rather what was requested by the author: "PS: -The variable cannot be defined in the main function, because the getNumber function will be called elsewhere as well"

  • Yes, of course. He’s having trouble even asking the question, imagine the correct requirement. Global variables were no problem 40, 50 years ago when codes were very small. Modern languages limit the use of the global state in a localized variable. C++ has a global variable per legacy but should not be used. Variables should not be used in "other places", they should be local. If the values need to be used elsewhere, ok, but then it should be passed as parameter. I even use global state but I know all the implications of doing this, it’s relatively rare who knows.

  • That’s not what I meant, but perhaps my effort to try to explain has become futile.

4

Variables in C/C++ cannot 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 whether the variable has been defined, because there is no need.

As per your example, all you have to do is set the variable before the function and remove the bool who is in the else. Note that bool check is out of main() so that you can come to 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 how did you post the code #ifndef is used to check if MACRO has been set (this is not a variable) and as Maniero quoted, this is only used at compile time, so it does not have the same purpose as the variables.

Read about in: http://en.wikipedia.org/wiki/C_preprocessor#Macro_definition_and_expansion

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

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

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

You can quickly set in a global file a MACRO to tell if the application is production (being used by "people") or development (you are servicing or creating it).

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.