今天我发现了一件有趣的事情.我不知道在goto标签之后无法声明变量.
编译以下代码
#include <stdio.h>
int main() {
int x = 5;
goto JUMP;
printf("x is : %d\n",x);
JUMP:
int a = 0; <=== giving me all sorts of error..
printf("%d",a);
}
Run Code Online (Sandbox Code Playgroud)
给出错误
temp.c: In function ‘main’:
temp.c:7: error: expected expression before ‘int’
temp.c:8: error: ‘a’ undeclared (first use in this function)
temp.c:8: error: (Each undeclared identifier is reported only once
temp.c:8: error: for each function it appears in.)
Run Code Online (Sandbox Code Playgroud)
那背后的逻辑是什么?我听说无法在switch的case语句中创建变量.由于JUMP是goto语句的同一范围(主要功能的范围,在我的情况)里面,我相信,范围是不是一个问题在这里.但是,为什么我会收到此错误?
请考虑以下程序(请参阅此处的实时演示).
#include <stdio.h>
int main(void)
{
int ; // Missing variable name
puts("Surprise");
}
Run Code Online (Sandbox Code Playgroud)
我的编译器gcc 4.8.1给出了以下警告:
[警告]空声明中无用的类型名称[默认启用]
为什么编译好?我不应该得到编译错误吗?当我将它编译为C++程序时,g ++ 4.8.1给出以下错误:
[错误]声明没有声明任何内容[-fpermissive]
我想这样做,但它不会编译:
Public MyVariable as Integer = 123
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最佳方法是什么?
bar1和和的类型有什么区别bar2?
int foo = 10;
auto bar1 = &foo;
auto *bar2 = &foo;
Run Code Online (Sandbox Code Playgroud)
如果这两个bar1和bar2是int*,确实是有意义的写指针声明符(*)在bar2声明?
我看到实用的Common Lisp使用(defvar *db* nil)设立一个全局变量.是否可以setq用于同一目的?
使用defvarvs. 的优点/缺点是setq什么?
鉴于以下内容:
// not a problem
int i = 2, j = 3;
Run Code Online (Sandbox Code Playgroud)
这让我感到惊讶:
// compiler error: Implicitly-typed local variables cannot have multiple declarators
var i = 2, j = 3;
Run Code Online (Sandbox Code Playgroud)
不编译.也许有一些我不明白的事情(这就是我问这个的原因)?
但为什么编译器不会意识到我的意思:
var i = 2;
var j = 3;
Run Code Online (Sandbox Code Playgroud)
哪个会编译.
如果在声明中初始化了非静态数据成员,它们是否允许将非静态数据成员声明为"auto"?例如:
struct S
{
auto x = 5; // in place of 'int x = 5;', which is definitely allowed
};
Run Code Online (Sandbox Code Playgroud)
GCC 4.7拒绝上述代码,但它接受了int x = 5;.
假设这不是编译器错误,而是标准真的不允许它,为什么不呢?它与声明局部变量一样有用auto.
此代码编译,但我在Visual Studio中有运行时错误:
运行时检查失败#3 - 正在使用变量'x'而未初始化...
int x = 15;
int main()
{
int x = x;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我不明白这种行为...当我点击继续时错误框中的程序恢复,x有一个损坏的内容(比如-8556328代替15).
为什么这段代码没有问题,并且int数组声明得很好?
const int x = 5;
int main()
{
int x[x] = {1,2,3,4};
return 0;
}
Run Code Online (Sandbox Code Playgroud) 如果您查看语法,*declarator*s in §8/4您会注意到a noptr-declarator可以写成(ptr-declarator),也就是说,它可以写成(declarator-id),它可以验证标题中的声明.事实上,这段代码编译没有问题:
#include <iostream>
struct A{ int i;};
int (x) = 100;
A (a) = {2};
int main()
{
std::cout << x << '\n';
std::cout << a.i << '\n';
}
Run Code Online (Sandbox Code Playgroud)
但是当声明中没有涉及指针(数组或函数)时允许这些括号的目的是什么?
我们的内部审计建议我们使用显式变量类型声明而不是使用关键字var.他们认为使用var"可能会在某些情况下导致意外结果".
var一旦代码编译成MSIL,我不知道显式类型声明和使用之间的任何区别.
审计员是一位受人尊敬的专业人士,所以我不能简单地拒绝这样的建议.