简体   繁体   English

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

[英]Error: 'for' loop declarations only in c99 mode

I am trying to compile this C code in my linux system (I am new to all of this) and I keep getting this error:我正在尝试在我的 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

I tried declaring int i before the for loop, but got this error:我尝试在 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;

   ^

This is the code:这是代码:

#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");

    }
}
``

Either set the option of the compiler that allows to compile code as a C99 code (or C11, or C18).设置允许将代码编译为 C99 代码(或 C11 或 C18)的编译器选项。 Or rewrite this part of the code:或者重写这部分代码:

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

the following way以下方式

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

That is, enclose the compound statement in this code snippet in braces.也就是说,将此代码片段中的复合语句括在大括号中。 Then the label will not precede a declaration.那么标签将不会出现在声明之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM