gpt4 book ai didi

c - 错误: 'for' loop declarations only in c99 mode

转载 作者:行者123 更新时间:2023-12-02 10:52:26 25 4
gpt4 key购买 nike

我正在尝试在我的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");

}
}
``

最佳答案

要么设置允许将代码编译为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;
}
也就是说,将复合语句括在该代码段中。这样,标签将不会在声明之前。

关于c - 错误: 'for' loop declarations only in c99 mode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64379590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com