Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show error in function if some other function has not run before it

I have two functions in C library that I am making.
One is a setup function, other is a function that does some operations. I want the second operations function to print an error if the setup function has not run before it.
What would be the best way to do this?

Here is what I have in my mind, but I am not sure if that is how it is done.

The setup function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void setup_function()
{
    #ifndef FUNCTION_SETUP
    #define FUNCTION_SETUP
    a_init();
    b_init();
    c_init();
    #endif
}

And the operations function:

bool operations()
{
    #ifdef FUNCTION_SETUP
    try
    {
        /* My code */
        return true;
    }
    catch (...)
    {
        Serial.println("Error in operations");
        return false;
    }
    #elif Serial.println("Function not setup. Please use setup_function() in void setup()");
    #endif
}

>Solution :

#ifndef only checks whether this function was defined somewhere for the compiler and won’t affect runtime.

best way to do this is through use of a global variable that changes value once the setup function is executed. if you’re defining these functions in classes you could use static data member and setup function

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading