Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

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

I found a strange piece of C++ grammar on CodeSignal:

string r, longestDigitsPrefix(string s)
{
   for(auto const c : s)
   {
      if(isdigit(c))
        r += c;
      else
        break;
   }
   return r;
}

The first line is defining string r before the function declaration. Is this valid in modern C++?

The above code compiles and passes all tests in the CodeSignal console, but it produced a compiler error when I tried to compile locally (--std=c++14).

Is this is valid grammar in modern C++? If so, which standard revision does it comply with?

question from:https://stackoverflow.com/questions/54277381/is-it-legitimate-in-modern-c-to-define-a-return-variable-in-the-function-decla

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...