Void function doing return (void)(something)

1327 views c++
-2

I saw a few functions in an SDK I'm using do something similar to the following:

void foo( float& fl )
{
    if ( std::isnan( fl ) || std::isinf( fl ) )
        return ( void )( fl = 0.f );
    /*...*/
}

Why?

answered question

Because the author want to write this way? Why not?

there is no functional reason to write code this way, This works just as well: { fl = 0.f; return; }

The {} keys on their keyboard were broken?

My guess is the author decided this is more readable than adding some { } to encapsulate the assignment and return. I happen to disagree.

f1 is a reference parameter. Perhaps this is drawing attention to the fact that changing the value in the scope of this function also changes it externally.

2 Answers

3

    return ( void )( fl = 0.f );

Why?

That is rather unusual code. Casting an expression to void is usually done to suppress a compiler-warning -- it's an idiom that tells the compiler "yes, I know I am throwing this expression's value away -- but I'm doing it deliberately, so you don't need to warn me about it".

What is unusual there is that the author decided to do that in a return statement. It would have been clearer (and logically equivalent) to write

fl = 0.0f;
return;

instead. The only thing I can think of is that the function used to return a value, and perhaps the author thought he might someday want to change it to return a value again, and would therefore try to keep the code-style looking similar to that of a value-returning function? (If so, it seems a bit "too clever" to me)

posted this
3

It's the same as

void foo( float& fl )
{
    if ( std::isnan( fl ) || std::isinf( fl ) )
    {
        fl = 0.f;
        return;
    }
    /*...*/
}

there is no special reason to prefer one way than another.

posted this

Have an answer?

JD

Please login first before posting an answer.