Pedantic gcc warning: type qualifiers on function return type

前端 未结 8 538
名媛妹妹
名媛妹妹 2020-12-08 06:07

When I compiled my C++ code with GCC 4.3 for the first time, (after having compiled it successfully with no warnings on 4.1, 4.0, 3.4 with the -Wall -Wextra opt

8条回答
  •  萌比男神i
    2020-12-08 06:48

    Scott Meyers pointed out that there's pretty good reason why someone would want to return const values. Here's an example:

    int some_calculation(int a, int b) { int res = 0; /* ... */ return res; }
    
    /* Test if the result of the calculation equals 40.*/
    if (some_calculation(3,20) = 40)
    {
    
    }
    

    Do you see what I did wrong? This code is absolutely correct and should compile. The problem is that the compiler didn't understand that you intended tocompare instead of assign the value 40.

    With a const return value the above example won't compile. Well, at least if the compiler doesn't discard the const keyword.

提交回复
热议问题