Why does C++ code missing a formal argument name in a function definition compile without warnings?

前端 未结 4 741
闹比i
闹比i 2020-11-29 01:44

While getting started with some VS2005-generated MFC code, I noticed it overrode a method with something like this:

void OnDraw(CDC* /*pDC*/)
{
    ...
    /         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 02:18

    The most common reason I've seen is to suppress the unused variable warnings the compiler will throw up for:

    #include 
    
    void foo(int source)
    {
      std::cout << "foo()" << std::endl;
    }
    
    int main()
    {
      foo(5);
      return 0;
    }
    

    gcc says: main.cc:3: warning: unused parameter 'source'

    There are two common ways to get rid of the warning: comment the variable name or remove it entirely:

    void foo(int /*source*/)
    {
      std::cout << "foo()" << std::endl;
    }
    

    versus

    void foo(int)
    {
      std::cout << "foo()" << std::endl;
    }
    

    I highly recommend commenting over removing. Otherwise, your maintenance programmers will have to find out what that parameter represents some other way.

    Qt (and probably other frameworks) provides a macro that suppresses the warning without needed to comment or remove the variable name: Q_UNUSED():

    void foo(int source)
    {
      Q_UNUSED(source); // Removed in version 4.2 due to locusts
      std::cout << "foo()" << std::endl;
    }
    

    This lets you call out in the function body that the variable is not used, and gives a great place to document why it isn't used.

提交回复
热议问题