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

标签 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");

    }
}
``

最佳答案

要么设置允许将代码编译为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/

相关文章:

c++ - Switch 语句仅适用于某些情况

javascript - 增加我的密码长度进度条

c - C语言中没有指向单个字符的指针吗?

c - 地址占用多少字节?

c - 遍历矩阵的相邻对角线

vba - 编译错误 vba - 我想覆盖它

c# - 如何在 C# 中的 switch case 中使用 web.config 值而不使用 if ,否则循环 "A constant value is expected."

c - 你如何处理从 getopt 中获取参数的顺序?

java - Java多个文件和文件夹层次结构

scala - 从 scala 代码中使用 Google guava 时出现编译器错误