Why is a function without argument identifiers valid in C++?

Consider a case where you are required to provide a function that meets the following prototype

void dostuff(int x, int y, int z);

And say you are operating in a 2D space and do not use z inside your implementation. You can

void dostuff(int x, int y, int z)
{
    // use x and y
}

and just ignore z, but the compiler will likely spot that you have defined but not used z and warn you that you could be making a mistake. Instead you can

void dostuff(int x, int y, int )
{
    // use x and y
}

and leave out the definition of z. The compiler will accept and silently discard the third parameter because it knows you don’t want it.

You do not want to simply turn off the warning because of errors like this

void dostuff(int x, int y, int z)
{
    for (int z = 0; z < MAX; z++)
    {
        // use x and y and z, the local z. 
    }
}

Where a poorly-named loop index shadows the parameter z. The caller’s input is now ignored and this could have bad consequences. This error is often hard to spot with the mark 1 eyeball, especially if the local z is buried somewhere deep in a complex function.

Anytime the compiler can pick off a possible bug in your code, take advantage. It means less work for you.

Leave a Comment