For loop says expression syntax error when initializing integer in the loop
While programming I have come to an unusual error. When I initialize an integer in a loop, sometimes it says that the expression is not valid, but at times it accepts it. This is my code which gives error:
int pow(int x,int n);
int main()
{
int x,n,result;
printf("Enter a number:\n");
scanf("%d",&x);
printf("Enter its power:\n");
scanf("%d",&n);
result=pow(x,n);
printf("Result is %d\n",result);
getch();
return 0;
}
int pow(int x,int n)
{
for(int i=1;i<n;i++) //<-- here it says that declaration syntax error
x=x*i;
return x;
}
While when i c开发者_C百科hange it like this :
int pow(int x,int n)
{
int i;
for(i=1;i<n;i++)
x=x*i;
return x;
}
C89 and earlier versions only support declaration statements at the head of a block (IOW, the only thing that can appear between an opening {
and a declaration is another declaration):
/* C89 and earlier */
int main(void)
{
int x; /* this is legal */
...
for (x = 0; x < 10; x++)
{
int i; /* so is this */
printf("x = %d\n", x);
int j = 2*x; /* ILLEGAL */
}
int y; /* ILLEGAL */
...
}
With C99, declaration statements can appear pretty much anywhere, including control expressions (with the caveat that something must be declared before it is used):
// C99 and later, C++
int main(void)
{
int x; // same as before
...
for (int i = 0; i < 10; i++) // supported as of C99
{
printf("i = %d\n", i);
int j = 2 * i; // supported as of C99
}
int y; // supported as of C99
}
Turbo C predates the C99 standard, so if you want to write code like in the second example, you will need to use a more up-to-date compiler.
In C, before C99, you need to declare your variables before your loop. In C++, and now in C99, you can declare them within the loop as you try here. The different results you are getting may be because you are sometimes compiling as C++, and sometimes compiling as C.
You could try to make sure you are always compiling your code as C++, or if you're using GCC or Clang, compile with the --std=c99
flag. C99 is unsupported by MSVC, so you will either need to use C++ or move the declaration outside of the loop if you're using MSVC.
It sounds like you have a C89 compiler (rather than C99 compiler).
In C89, you are only allowed to declare variables at the beginning of a function. You are simply not allowed to declare variables elsewhere in a function, including in the initialization part of a for
statement. That's why the second syntax works and the first fails.
The second syntax is valid for C99 and C++ but not for C89.
What C compiler are you using?
Older versions of C prior to C99 require all variable declarations be made at the top of a code block.
精彩评论