当我在写一些 C++11 代码时:
#include <bits/stdc++.h>
using namespace std;
int a, b, array[25];
int function();
int main() {
... (not important)
出于好奇,我将变量声明与函数原型(prototype)放在同一行:#include <bits/stdc++.h>
using namespace std;
int function(), a, b, array[25];
int main() {
... (not important)
它在 XCode(设置为 [-std=c++11])和 a, b, array[]
上正确编译可以像普通变量/数组一样使用。这是否适用于大多数/所有编译器,这不鼓励/很好吗?为什么这在 C++ 中有效(函数原型(prototype)和变量声明似乎完全不同......)
提前感谢您的宝贵时间。
最佳答案
声明说 function(x)
, a
, b
, 和 array[i]
都是int
s。
(这是类型的“老派阅读”——它总是在 C 中工作,但 C++ 打破了它;int *x
可以阅读“*x
是 int
”,但 int &x
无法阅读“&x
是 int
”。)
自从 C 的早期(所以,半个世纪左右)以来,这一直很好,并且不仅限于全局声明。
这也很困惑,你不会发现很多人认为这是个好主意。
大多数人现在已经放弃在一行中声明多个变量。
它的可读性较差,容易忘记初始化程序,并且这些天屏幕能够同时显示多行。
关于c++ - 在 C++11 中,可以在同一行声明全局变量和函数原型(prototype)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63499626/