Changed the question, HELP ASAP PLEASE

How can I force program to end when a specific function is called for the second time ??

//EDİT: okay I understood that I can't do that.. Help me with this please.


I need to end the program when the variable vegetable is eggplant but if it's tomato the program needs to call a function. I tried something but I guess it was nonsense. It keeps calling the Which() function without caring the variable.

1
2
3
4
5
6
7
cout << name << ", you should pay " << pay << " TL to buy " << weight << " kg of " << vegetable << " and you will be left with " << change << " TL."<<endl;
		cout << endl;

		if (vegetable == "tomato")
		{
			Which(name, change, "eggplant");
		}
Last edited on
You can use standard function std::exit from cstdlib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

void callOnce()
{
    static bool calledBefore = false;
    if (calledBefore)
        exit(1);
    calledBefore = true;
    //rest of function
}

int main()
{
    callOnce();
    std::cout << "first call" << std::endl;
    callOnce();
    std::cout << "second call" << std::endl;
}
You will never see "second call" because program will stop before that.
Last edited on
I'm not skilled enough to use it I guess.
Last edited on
Normally the program ends when you leave the main function. You can use std::exit but note that that will not destroy any objects with automatic storage duration.
You can use std::exit but note that that will not destroy any objects with automatic storage duration.
And OS will take care of that instead in most cases. When you get to the point where it isn't the case, you will have enough experience to use it wisely.

EDIT: http://en.cppreference.com/w/cpp/utility/program/exit ← that article tells that std::exit does cleanup.
Last edited on
MiiNiPaa wrote:
And OS will take care of that instead in most cases. When you get to the point where it isn't the case, you will have enough experience to use it wisely.
It's more of a problem if the destructor does something other than just freeing memory e.g. writing to file.
Last edited on
Well yes, but this (http://en.cppreference.com/w/cpp/utility/program/exit) tells that
Several cleanup steps are performed:
destructors of objects with thread local storage duration are called
destructors of objects with static storage duration are called
So only std::quick_exit() will have this problem (and c-style exit() I have used and abort())
Last edited on
@MiiNiPaa
From the page you linked:
Destructors of variables with automatic storage durations are not called.
Whoops. Yes, you are right.
Looks like only way to safely do this is to throw an exception: if it won't be cautch, it will terminate program, but it will unwound stack and will normally destroy all objects.
Topic archived. No new replies allowed.