Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of a statement with no effect in C++? [duplicate]

Tags:

c++

templates

In one library that I am using I saw this code:

template<typename T>
void f(SomeTemplatedClass<T> input)
{
    (void)input;
    ...
    use(input); // code that uses input
}

I have no idea what is the meaning of this code. If I remove the cast to void, I get a

statement has no effect 

warning in gcc. So I suppose someone did it purposefully and purposefully added the cast to get a rid of the warning.

Do you have any experience with a statement that has no effect, yet it is needed for some reason?

EDIT:

Is it safe to assume that this has nothing to do with templates? For example circumventing an old compiler bug or the like?

like image 864
Martin Drozdik Avatar asked Oct 01 '22 06:10

Martin Drozdik


1 Answers

This construct is a common way of tricking the compiler into not emitting a warning for unused parameters. I have not seen it used for any other purpose.

(void)input;

While it is common, it is also a really bad idea.

  • it is highly platform dependent -- it may work on one compiler and not another.
  • it is unnecessary. There is always a better way to deal with unused parameters. The modern way is to simply omit the parameter name.
  • it can get left behind if the code changes and the parameter is now used (as appears to be the case here).
  • it can backfire. Some compilers may treat this as invalid.

According to the C++ standard N3936 S5.4/11:

In some contexts, an expression only appears for its side effects. Such an expression is called a discarded-value expression. The expression is evaluated and its value is discarded.

A compiler would be entitled to observe that there is no side-effect and therefore this construct deserves at least a warning. According to @chris, MSVC is one of those compilers.

like image 108
david.pfx Avatar answered Oct 22 '22 22:10

david.pfx