Rajesh M
Rajesh M

Reputation: 634

how to exit from a function but not from main()

Does C/C++ support terminating a program from a subroutine function i.e not main? So far I only found that exit and abort allow a user to terminate current function or process. If I'm not in main function, is there a way to terminate the whole program?

Upvotes: 4

Views: 7121

Answers (5)

Vijendra Singh
Vijendra Singh

Reputation: 628

void exit (int status)

Above method Terminates the process normally, performing the regular cleanup for terminating programs.

Normal program termination performs the following (in the same order):

  1. Objects associated with the current thread with thread storage duration are destroyed (C++11 only).

  2. Objects with static storage duration are destroyed (C++) and functions registered with atexit are called.

  3. All C streams (open with functions in ) are closed (and flushed, if buffered), and all files created with tmpfile are removed.

And after that Control is returned to the host environment.

As it terminates the calling process, becuase your function is part of same process, so using exit() in that will terminate the program.

Upvotes: 0

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

since you're talking C++, consider std::terminate

u now, for “Does C/C++ support terminating a program from a subroutine function i.e not main?”

by default std::terminate calls abort, but this is configurable by installing a handler via std::set_terminate

Upvotes: 1

Aleem Ahmad
Aleem Ahmad

Reputation: 2539

It can only be possible if you called that function from main function. And from that function from which you want to terminate the program return a value for terminating the program for example -1.

Example:

void main()
{
    //Call to a function
    int i = functionFromMain();
    if(i == -1)
    {
        //Terminate Program
    }
}

Upvotes: -2

Jeegar Patel
Jeegar Patel

Reputation: 27210

If you are not in main() and in other function then also you can call exit() or abort() it will terminate your whole process.

where exit() will do required clean up where abort() will not perform that.

Upvotes: 5

nommyravian
nommyravian

Reputation: 1336

exit(0) or exit(1)

If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure.

ref: See here

Upvotes: 1

Related Questions