Is it legitimate in modern C++ to define a return variable in the function declaration?

Yeah, C++ grammar is weird. Basically, when it comes to declarations (and only declarations), we have this thing where:

T D1, D2, ... ,Dn;

means ([dcl.dcl]/3):

T D1;
T D2;
...
T Dn;

This will be familiar in the normal cases:

int a, b; // declares two ints

And probably in the cases you’ve been told to worry about:

int* a, b, *c; // a and c are pointers to int, b is just an int

But declarators can introduce other things too:

int *a, b[10], (*c)[10], d(int);

Here a is a pointer to int, b is an array of 10 ints, c is a pointer to an array of 10 ints, and d is a function taking an int returning an int.


However, this only applies to declarations. So this:

string r, longestDigitsPrefix(string s);

is a valid C++ declaration that declares r to be a string and longestDigitsPrefix to be a function taking a string and returning a string.

But this:

string r, longestDigitsPrefix(string s) { return s; }

is invalid C++. Function definitions have their own grammar and cannot appear as part of the init-declarator-list.

The definition of that function is also bad, since it’s using a global variable to keep track of state. So even if it were valid, longestDigitsPrefix("12c") would return "12" the first time but "1212" the second time…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)