简体   繁体   中英

With C++ how do I Pass a value from a void function?

I have two C++ functions in a class:

void Attribute::setIndex(int inIndex) {
    if (inIndex < 0) {
        index = 0;
    }
    else if (inIndex >= MAX_NUM_ATTRIBUTES) {
        index = MAX_NUM_ATTRIBUTES - 1;
    }
    else {
        index = inIndex;
    }
}

and

int Attribute::getValueWithinRange(int value) {
    value = setIndex(value);
    return value;
}

The second function is supposed to use setIndex to set 'value' to the correct number and return it. However, since the first function is a void function, i cannot simply pas the value in the way i did above. Should i do pass by reference or are there any suggestions? Thank you very much.

I would like just to note, that if you are learning C++, you should try to learn model cases first, sometimes rushing examples is not the best way, but there we go:


Change the setIndex to return int, my favorite;

int Attribute::setIndex(int inIndex)
{
    if (inIndex < 0)
    {
        index = 0;
    }
    else if (inIndex >= MAX_NUM_ATTRIBUTES)
    {
        index = MAX_NUM_ATTRIBUTES - 1;
    }
    else
    {
        index = inIndex;
    }

    return index;
}


int Attribute::getValueWithinRange(int value)
{
    value = setIndex(value);
    return value;
}

Change the getValueWithinRange to return index, both methods are in one class, they share the access to index;

int Attribute::getValueWithinRange(int value)
{
    setIndex(value);
    return index;
}

Giving it reference would work, but you can not set reference to null unless using a trick and it would require unnecessarily another method, so pointer makes it less messy:

int Attribute::setIndex(int inIndex, int* ret_index = nullptr)
{
    if (inIndex < 0)
    {
        index = 0;
    }
    else if (inIndex >= MAX_NUM_ATTRIBUTES)
    {
        index = MAX_NUM_ATTRIBUTES - 1;
    }
    else
    {
        index = inIndex;
    } 

    if (ret_index != nullptr) *ret_index = index;

    return index;
}


int Attribute::getValueWithinRange(int value)
{
    int retvalue;
    setIndex(value); // use it like this when returning value is not needed
    setIndex(value, &retvalue);

    return retvalue;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM