簡體   English   中英

錯誤:'for' 循環聲明僅在 c99 模式下

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

我正在嘗試在我的 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;
    }

也就是說,將此代碼片段中的復合語句括在大括號中。 那么標簽將不會出現在聲明之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM