For loop says expression of syntax error when initializing integer in loop

During programming, I came up with an unusual error. When I initialize an integer in a loop, sometimes it says that the expression is invalid, but sometimes it takes it. This is my code that gives an 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 I change it like this:

int pow(int x,int n)
{   
    int i;
    for(i=1;i<n;i++)  
    x=x*i;
    return x;
}
+5
source share
4 answers

C89 and earlier versions only support block-headed declaration declarations (IOW, the only thing that can appear between opening {and declaring 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 almost everywhere, including control expressions (with the proviso that something must be announced before using it):

// 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 C99, , , , .

+8

C C99 . ++, C99, , . , , , ++, C.

, ++ GCC Clang, --std=c99. C99 MSVC, ++ , MSVC.

+9

, C89 ( C99).

In C89, you are allowed to declare variables at the beginning of a function. You are simply not allowed to declare variables elsewhere in the function, including in terms of initializing the statement for. This is why the second syntax works and the first crashes.

The second syntax is valid for C99 and C ++, but not for C89.

+5
source

Which C compiler are you using?

Older versions of C to C99 require all variable declarations to be made at the top of the code block.

+2
source

All Articles