Why cast unused return values to void?

后端 未结 9 1362
暗喜
暗喜 2020-11-22 09:00
int fn();

void whatever()
{
    (void) fn();
}

Is there any reason for casting an unused return value to void, or am I right in thinking it\'s a c

9条回答
  •  故里飘歌
    2020-11-22 09:58

    Casting to void is used to suppress compiler warnings for unused variables and unsaved return values or expressions.

    The Standard(2003) says in §5.2.9/4 says,

    Any expression can be explicitly converted to type “cv void.” The expression value is discarded.

    So you can write :

    //suppressing unused variable warnings
    static_cast(unusedVar);
    static_cast(unusedVar);
    static_cast(unusedVar);
    
    //suppressing return value warnings
    static_cast(fn());
    static_cast(fn());
    static_cast(fn());
    
    //suppressing unsaved expressions
    static_cast(a + b * 10);
    static_cast( x &&y || z);
    static_cast( m | n + fn());
    

    All forms are valid. I usually make it shorter as:

    //suppressing  expressions
    (void)(unusedVar);
    (void)(fn());
    (void)(x &&y || z);
    

    Its also okay.

提交回复
热议问题