错误:仅在c99模式下“ for”循环声明

时间:2020-10-15 20:59:59

标签: c compiler-errors switch-statement label declaration

我正在尝试在我的linux系统中编译此C代码(我是所有这些的新手),并且不断收到此错误:

ForkCall.c: In function ‘main’:
  ForkCall.c:70:1: error: ‘for’ loop initial declarations are only allowed in C99 mode
    for (int i=1; i<=5; i++)
    ^
  ForkCall.c:70:1: note: use option -std=c99 or -std=gnu99 to compile your code

我尝试在for循环之前声明int i,但收到此错误:

ForkCall.c: In function ‘main’:
  ForkCall.c:69:1: error: a label can only be part of a statement and a declaration is 
  not a statement
   int i;

   ^

这是代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
    pid_t pid, pid2;
    int n;

    printf("Select a number [1-5]: ") ;
    scanf("%d", &n);
    printf("\n\n");

    switch(n)
    {
    case 1:
        fork();
        printf("This is process %d\n", getpid());
        break;

    case 2:
        fork(); fork();
        printf("This is process %d\n", getpid());
        break;

    case 3:
        fork(); fork(); fork();
        printf("This is process %d\n", getpid());
        break;

    case 4:
        if((pid=fork()) && (pid2 = fork())) {fork();}
        if((pid=fork()) && (pid2 = fork())) {fork();}
        if ((pid=fork()) && (pid2 = fork())) {fork();}
        printf("This is process %d\n", getpid());
        break;

    case 5:
        for (int i=1; i<=5; i++)
        {
            fork();
        }
        printf("This is process %d\n", getpid());
        break;

    default:
        printf("Number not in range [1-5] !\n");

    }
}
``

1 个答案:

答案 0 :(得分:1)

要么设置允许将代码编译为C99代码(或C11或C18)的编译器选项。或重写这段代码:

    case 5:
        for (int i=1; i<=5; i++)
        {
        fork();
        }
        printf("This is process %d\n", getpid());
        break;

以下方式

    case 5:
    {
        int i = 1;
        for ( ; i<=5; i++)
        {
            fork();
        }
        printf("This is process %d\n", getpid());
        break;
    }

也就是说,将复合语句括在大括号中。那么标签将不会在声明之前。