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

前端 未结 5 2031
粉色の甜心
粉色の甜心 2021-02-06 22:05

Given a function in C++ with arguments that are only types and have no identifiers,

 void foo1(int, int, int){cout << \"called foo1\";}

I

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 22:19

    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.

提交回复
热议问题