This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Feature request: issue a warning when function declaration looks like variable definition


The following problem is very common when dealing with iterators,
function objects and/or algorithms in C++. This is a simple test case:

#include <iostream>
#include <iterator>
#include <string>

int main() {
  using namespace std;
  typedef istreambuf_iterator<char> isbi;
  string str(isbi(cin), isbi());           // Line 8
  cout << str << endl;                     // Line 9
}

The code above, even though it looks correct to experienced C++
programmer and compiles fine, does definitely not do what the programmer
intended it to.

The program was meant to read all characters from std::cin, until EOF,
into str. Instead, it reads nothing from there and just prints value 1
to std::cout, as also suggested this warning message (enabled by -Wall):

test.cpp:9: warning: the address of âstd::string str(main()::isbi,
main()::isbi (*)())â will always evaluate as âtrueâ

This message may tell an experienced C++ programmer what the actual
problem is, but even then it points at the wrong line. Depending on how
str is used, there might be even more obscure errors, especially if str
is passed to a template function.

The problem here is that the C++ standard requires line 8 to be
interpreted as a declaration of a function named str, returning string
and taking two arguments of type isbi (the first one is named cin and
the second one is anonymous). The extra parenthesis around variable
names are ignored.

However, since it is not conventional to use parenthesis around variable
names in function declarations, this problem could be analyzed by GCC,
issuing a proper warning.

My suggestion:

Whenever a function declaration with parenthesis around parameter names
is seen, issue a warning:

<file>:<lineno>: warning: '<symbolname>' is interpreted as a function
declaration, but it looks like a variable definition (put parenthesis
around '<first argument>' to make it so)

E.g. in the above case:

test.cc:8: warning: 'str' is interpreted as a function declaration, but
it looks like a variable definition (put parenthesis around 'isbi(cin)'
to make it so)

Note: the case of variable initialization without arguments (also
interpreted as a function declaration) cannot be diagnosed in this
manner. Therefore no warning should be issued on this: string str();
People generally learn to write just string str; rather quickly.



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]