[英]Defining a function and a variable in one declaration statement
I am pretty sure the following is legal 我很确定以下是合法的
int a, *b, c[5], d(char x);
This defines an integer a
, a pointer to int b
, an array of 5 ints c
, and declares a function d
taking a char and returning int. 它定义了一个整数
a
,一个指向int b
的指针,一个由5个int c
的数组,并声明了一个带有字符char并返回int的函数d
。
Is it legal to provide the definition of the function there as well? 在那里也提供功能定义是否合法? (provided we're not in function scope)
(前提是我们不在功能范围内)
int a, f()
{
return 1;
}
int main()
{
cout << a << f(); //prints 01;
}
MSVC rejects the code. MSVC拒绝该代码。 If it's right to do so, I am wondering which rule in the standard allows such function declarations but not definitions.
如果这样做是正确的,我想知道标准中的哪个规则允许这样的函数声明,但不允许定义。
I am trying to do a codegolf-style challenge and I need to minimize my code in terms of characters and I was wondering if this trick is legal C++. 我正在尝试进行代码高尔夫风格的挑战,我需要根据字符将代码最小化,我想知道此技巧是否合法的C ++。
No, a function definition only has a single declarator. 不,一个函数定义只有一个声明符。 It's specified in C++11 8.4.1 and A.7:
它在C ++ 11 8.4.1和A.7中指定:
function-definition:
attribute-specifier-seq<opt> decl-specifier-seq<opt> declarator virt-specifier-seq<opt> function-body
int a, *b, c[5], d(char x);
Is valid because the compiler knows you will not declare any variables anymore. 有效,因为编译器知道您将不再声明任何变量。 The compiler knows this because there is a semicolon standing behind the statement.
编译器知道这一点,因为该语句后面有一个分号。
int a, f()
{
return 1;
}
Is in valid because the compiler doesn't know when you are declaring the variable and the function. 是有效的,因为当你在声明变量和函数,编译器不知道。 And when you start the implemantation of the function;(It thinks you want to declare everything from the
int
to the first semicolon after return 1
as a variable). 并且当您开始执行该函数时(它认为您想声明从
int
到return 1
作为变量后的第一个分号的所有内容)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.