簡體   English   中英

錯誤:此處不允許定義函數。 如何糾正這個?

[英]Error: function definition is not allowed here. How to correct this?

這是代碼:

#include<stdio.h>

int main(){

// prints I stars

void printIStars(int i) {

  // Count (call it j) from 1 to i (inclusive)

  for (int j = 1; j <= i; j++) {

    // Print a star

    printf("*");

  }

}


// prints a triangle of n stars

void printStarTriangle(int n) {

  // Count (call it i) from 1 to n (inclusive)

  for (int i = 1; i <= n; i++) {

    // Print I stars

    printIStars (i);

    // Print a newline

    printf("\n");

  }

}

return 0;

}

對於這兩個功能,我都收到錯誤

“此處不允許定義函數”

如何糾正這個?

您在main函數內部定義了兩個函數, printIStarsprintStarTriangle ,這是每個 C 實現都不允許的。 GCC 允許將其作為擴展名,但 fe Clang 不允許。 當我使用 Clang 編譯您的代碼時,我收到兩個嵌套函數定義的相同警告。 因此,您可能使用 Clang 或其他不支持嵌套函數定義的實現。

main之外定義兩個函數,它們在每個實現中都起作用。

除此之外,您從未調用過其中一個函數。

所以這是一個工作示例:

#include <stdio.h>

// function prototypes.
void printIStars(int i);              
void printStarTriangle(int n);

int main (void)
{
    printIStars(4);
    puts("");         // print a newline.
    printStarTriangle(7);
    return 0;
}

// function definitions

// prints I stars
void printIStars(int i) {

  // Count (call it j) from 1 to i (inclusive)
  for (int j = 1; j <= i; j++) {

    // Print a star
    printf("*");
  }
}


// prints a triangle of n stars
void printStarTriangle(int n) {

  // Count (call it i) from 1 to n (inclusive)

  for (int i = 1; i <= n; i++) {

    // Print I stars
    printIStars (i);

    // Print a newline
    printf("\n");
  }
}

輸出:

****
*
**
***
****
*****
******
*******

暫無
暫無

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

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