错误:此处不允许函数定义。如何纠正这个问题?

Ami*_*rti 1 c nested function nested-function function-definition

这是代码:

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

}
Run Code Online (Sandbox Code Playgroud)

对于这两个函数我都收到错误

“此处不允许函数定义”

如何纠正这个问题?

Rob*_*rtS 6

您在函数内部定义了两个函数printIStars和,这是每个 C 实现都不允许的。GCC 允许将其作为扩展,但 fe Clang 不允许。当我使用 Clang 编译代码时,我对两个嵌套函数定义都收到相同的警告。因此,您可能使用 Clang 或其他不支持嵌套函数定义的实现。printStarTrianglemain

定义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");
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

****
*
**
***
****
*****
******
*******
Run Code Online (Sandbox Code Playgroud)