Home > database >  C How to force compiling error with improper use of function/method?
C How to force compiling error with improper use of function/method?

Time:12-29

Is there a way to force a compilation error? I want to be able to put conditions on a class method to prevent improper use of it. Current I am using return; to break out of the method, but the program will compile and run without the user of the function being aware that it is not being used properly.

Here is some sample code to show the situation:

void method(int x){
  if(x<5)
    return; //breaks out of method without executing anything below
...
more code
...
}

If x=4 the program would execute and run, however it may not be obvious that this method is not doing anything.

Thanks, Daniel

CodePudding user response:

This comment answered/corrected what I was trying to do:

force a compilation error? I'm not sure what you mean, but if you want your error to stop the program and you want to know what error, you can print to cerr and use exit() or abort(), or you could throw an exception with/without catching it – Asphodel

CodePudding user response:

I doubt compilation error is what you are looking for. Compilation error implies that the check(x < 5) can be done at compile time. However, currently this can not be done with your code.

What you could do is to use a runtime exception:

void method(int x)
{
    if(x < 5)
    {
        throw std::invalid_argument("X must not be less than 5!");
    }
      ⋮
      ⋮
}

Now, if someone called method with something lower than 5, the program will be stopped, and will print something like:

terminate called after throwing an instance of 'std::invalid_argument'
  what():  X must not be less than 5!

And if the user knows what they are doing, and knows using an argument lower than 5 is fine, and just wants to skip the rest of method, then they can use a try-catch:

int main()
{
    try {
        method(4);
    }
    catch (const std::invalid_argument& e) {
        std::cout << e.what(); // manually prints the error message

        // something to do instead.
              ⋮
              ⋮
    }
}

CodePudding user response:

When your program executes it is too late to make your program fail to compile, unless you have access to a time machine. Looks like you need a method to terminate execution of the running program. There are various ways to do that. Most proper is to use C exception (either to use system exceptions like std::runtime_error or define your own). If exceptions are not available due to various issues you can use std::abort() function which will terminate the program immediately. Though last method is not recommended as destructors of existing objects would not be called and your program may not terminate properly (cleaning some resources for example that are done in destructors would be omitted).

  • Related