为什么我得到“错误未声明的标识符”,除非我在开​​头声明我的变量?

我有以下时间:

#include "stdafx.h" #include int main() { int val1,val2; printf("Enter the first value"); scanf("%d",val1); scanf("%d",&val2); int c; c=val1 + val2; printf(" the value is : %d", c); return 0; // 0 means no error } 

我得到错误未声明的标识符c。 另外,语法错误。 失踪 ; 在类型之前。

但是,如果我更改以上错误消失。 请帮忙

 #include "stdafx.h" #include int main() { int val1,val2,c; printf("Enter the first value"); scanf("%d",&val1); scanf("%d",&val2); c=val1 + val2; printf(" the value is : %d", c); return 0; // 0 means no error } 

我在VS 2010中运行C语言。

在C中,至少在过去,变量声明必须位于块的顶部。 在这方面,C ++是不同的。

编辑 – 显然C99在这方面与C90不同(在这个问题上C99与C ++基本相同)。

对象只能在ISO C90中的语句块顶部声明。 你可以这样做:

 #include int main() { int val1,val2; printf("Enter the first value"); scanf("%d",val1); scanf("%d",&val2); // New statement block { int c; c=val1 + val2; printf(" the value is : %d", c); } return 0; // 0 means no error } 

虽然这样做可能很不寻常。 与某种流行的看法相反,函数的开始并不是唯一可以声明自动变量的地方。 例如,使用作为iffor构造的一部分引入的现有语句块,更常见的是,而不是创建虚拟块

case块括在{…}中是很有用的,即使通常不是必需的,这样您就可以引入临时的特定于案例的变量:

 switch( x ) { case SOMETHING : { int case_local = 0 ; } break ; ... } 

Microsoft决定不支持更新的C语言版本,因此您不能混合使用代码和声明。 使用MSVC,你基本上坚持使用C90,虽然支持一些选定的function(例如long longrestrict )。

我的建议是切换到C ++或使用不同的编译器,如GCC的MinGW版本 。

另一个观察。 scanf()想要目的地的ADDRESS,而不是它的值。

在上面的示例中,您省略了 in scanf(“%d”,val1); 。 在底部示例中,它包括scanf(“%d”,&val1);

“val1”vs“&val1”

不应该用变量’c’来改变问题,但可能会在某处导致语法错误?

在C90中,必须在function块的开头声明局部变量。