Is it possible to stop the lets say for loop with a function :

for(int i = 0;i<15;i++){

cin >> input;
obj.add(input);

}


// and then have some add or some other function that checks if (x == max_size)

check(){

   if(counter == max_size)
   stop the foor loop and continue..

}

Recommended Answers

All 6 Replies

Member Avatar for iamthwee

Possible yes... or you could use a do while loop.

no, it shoudn't be done in main.cpp, but in a function in implementation file ?

Do you want to return an result from the function that indicates whether to stop or do you want to divert local control flow from within a function call?

The former is entirely possible. The latter would require tricks and be non-portable.

i want it from within a function call. In my main part I will use for loop to insert el in array and in the end function will check is it full, if yes function will break from for loop and main course of program will cont. how can i do that?

Member Avatar for iamthwee

no, it shoudn't be done in main.cpp, but in a function in implementation file ?

Tell us why?

use return codes ? and then divert control. or you can do macro "magic" but in my opinion macro "magic" looks ugly.

bool check_if_done(args)
{
    if(args == something)
    {
        return false;
    }
    return true;
}

skip ahead inside your loop

loop{

    bool isDone = check_if_done(args);
    if(isDone == true)
    {
        //do something like break or condition fullfillment here to divert
        //control
    }



//Macro Magic
#include <iostream>
//ugly() is loop agnostic and should be able to be defined in an
//external compilation unit (if my memory serves me right)
#define ugly() std::cout << "I cheated" << std::endl; break;

int main(int argc, char ** argv)
{
    for(;;)
    {
        std::cout << "I'm an infinite loop, mwahwhahaha you can't escape";
        std::cout << std::endl;
        ugly();
    }
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.