Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a returning function from execution if a condition on parameters is true

Tags:

c++

like said on the title, I was wondering if it was possible to stop a function from execution. In my particular case, I'm trying to make an operator[] and prevent utilisator from using it if the value gave in parameters is too high :

in .h:

class Vec4
{
    float x,y,z,w;

    public:

        float operator[](const unsigned int i);
}

in .cpp :

float Vec4::operator[](const unsigned int i)
{
    if(i == 0) return x;
    if(i == 1) return y;
    if(i == 2) return z;
    if(i == 3) return w;
}

I'd like to "break" the function if i >=4 For the moment I'm just making a console output and return 0.0f

thank you to show me if there is a way ... or not !

like image 423
e.farman Avatar asked Jan 07 '17 21:01

e.farman


People also ask

How do you stop a JavaScript function when a certain condition is met?

Using return is the easiest way to exit a function. You can use return by itself or even return a value.

How do you stop a function execution?

Complete HTML/CSS Course 2022 To stop the execution of a function in JavaScript, use the clearTimeout() method. This function call clears any timer set by the setTimeout() functions.

How do you stop a function if a condition is met Python?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

How do you stop a function from returning in Python?

To prevent a function from returning None in Python, make sure to return a value from the function. All functions that don't explicitly return a value return None in Python.


1 Answers

You can do at least 4 things.

  1. Return a known error value from the function. For eg. -1 if the input value is no good.
  2. Raise an exception.
  3. Change the function to pass output by reference and return an error code.
  4. Force the user to get the point with a strongly typed enum class.

Option 1

float Vec4::operator[](const unsigned int i) {
    switch (i)
    case 0: 
      return x;
    ...
    default:
        return nan;

Option 2

default:
    throw InvalidInputException;

Option 3

typedef ErrCode int;
const int ERROR = -1;
const int SUCCESS = 1;
...
ErrCode Vec4::getPoint(const unsigned int i, float &ouptut) {
    ...
    switch (i)
    case 0: 
      output = x;
      return SUCCESS;
    default:
      return ERROR;

Option 4 (c++11)

class Vec4 {
...
public:
    enum class VecMem {X, Y, Z, W};
    float Vec4::getPoint(VecMem member) {
        switch (member):
            case X:
                return x;
        ...

Usage:

Vec4.getPoint(Vec4::VecMem::X); 
like image 77
Fantastic Mr Fox Avatar answered Sep 20 '22 13:09

Fantastic Mr Fox