Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I terminate (or return from) an auto function with a structure type during execution?

How do I terminate an "auto" type function with a structure return type during execution?

I want to escape the auto function 'Func' (not the entire program) when some condition is satisfied as follows:

#include "stdafx.h"
#include <vector>
#include <tchar.h>
#include <iostream>

using namespace std;

auto Func(int B, vector<int> A) {
    for (int a = 0; a < B; a++)
    {
        A.push_back(a);
        if (a == 2)
        {
            cout << " Terminate Func! " << endl;
            // return; I want to terminate 'Func' at this point  
        }
    }

    struct result { vector <int> A; int B; };
    return result{ A, B };
}

int _tmain(int argc, _TCHAR* argv[])
{

    vector<int> A;
    int B = 5;

    auto result = Func(B, A);
    A = result.A;
    B = result.B;

    for (int a = 0; a < A.size(); a++)
    {
        cout << A[a] << endl;
    }
}

I don't want to use "exit()" because I just want to terminate a function not the program.

like image 539
Angel Choi Avatar asked Jun 21 '19 07:06

Angel Choi


People also ask

How do you terminate a program from a function?

The exit() is a function and not a command. Unlike the return statement, it will cause a program to stop execution even in a function. And the exit() function can also return a value when executed, like the return statement. So the C family has three ways to end the program: exit(), return, and final closing brace.

How do you break out of a function in C++?

We know we can break out of loops using the built-in break function in C++. Similarly, we can also break out of a whole C++ program using the exit() function.

What is exit () function in C?

The exit () function is used to break out of a loop. This function causes an immediate termination of the entire program done by the operation system. The general form of the exit() function is as follows − void exit (int code);

Should I use exit or return?

return is a statement that returns the control of the flow of execution to the function which is calling. Exit statement terminates the program at the point it is used.


1 Answers

You can return a define the return type result at the top of the function and then return an "empty" instance like this:

auto Func(int B, vector<int> A) {
    struct result { vector <int> A; int B; };

    for (int a = 0; a < B; a++)
    {
        A.push_back(a);
        if (a == 2)
        {
            return result{{}, 0};
        }
    }

    return result{ A, B };
}

If you don't want a valid object to be returned when the early-return condition is met, consider returning a std::optional<result> from the function, and specifically std::nullopt in the early return branch. But this requires C++17.

like image 85
lubgr Avatar answered Oct 18 '22 03:10

lubgr