I have a problem compiling the following code:
#include <stdio.h>
#include <limits.h>
int main () {
printf("short: [%d,%d]\n",SHRT_MIN,SHRT_MAX);
printf("int: [%d, %d]\n",INT_MIN, INT_MAX);
printf("long: [%d, %d]\n",LONG_MIN,LONG_MAX);
int aa=017;
printf("%d\n",aa);
return 0;
}
Error message is:
1>c:\tic\ex1\ex2\ex2.c(12) : error C2143: syntax error : missing ';' before 'type'
1>c:\tic\ex1\ex2\ex2.c(13) : error C2065: 'aa' : undeclared identifier
However, compilation for this is fine:
#include <stdio.h>
#include <limits.h>
int main () {
int aa=017;
printf("short: [%d,%d]\n",SHRT_MIN,SHRT_MAX);
printf("int: [%d, %d]\n",INT_MIN, INT_MAX);
printf("long: [%d, %d]\n",LONG_MIN,LONG_MAX);
printf("%d\n",aa);
return 0;
}
Any idea what the issue is?
change the file type to cpp then it will work (and you can add c++ to your resume)
In (old) C, you cannot declare a variable anywhere as you can in C++ or in the latest C standards. You have to declare it directly after the open curly brace of a scope, as in your second example.
In C, variables previously had to be declared at the top of the scope, before any code is executed. This isn't the case in C99 (which Visual Studio doesn't implement.)
In C prior to C99, all variables in a given scope have to be defined before other statements in that scope. Though it initially looks the same, this isn't quite the same as GMan's answer. In particular, a function can contain other blocks that define other scopes, and those can define variables after executable statements in the outer block:
While defining a block like this (that's not associated with any flow control like an if statement or while loop) is fairly uncommon, it is allowed as a part of C.
Unless you explicitly tell it to compile as C, doesn;t visual studio compile .c files as c++ anyway? You can certainly use // commnets
In "classic" C language (C89/90) declarations are not allowed to appear in the middle of the code. Your original declaration of
aa
would be valid in C++ or in the "new" C (C99), but not in C89/90.VS 2008 comes with the C89/90 compiler, which is why you get these errors.
On top of that, the proper
printf
format specifier for pritinglong
values is%ld
, not%d
.