Search code examples
cfunctionnestednested-functionfunction-definition

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


Here is the code:

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

}

For both functions I get the error

"function definition is not allowed here"

How to correct this?


Solution

  • You define both functions, printIStars and printStarTriangle, inside of the main function which is not permissible by each and every C implementation. GCC allows that as extension but f.e. Clang doesn't. I get the same warning for both nested function definitions when I compile your code with Clang. So, you probably use Clang or another implementation which does not support nested function definitions.

    Define both functions outside of main which work at each implementation.

    Beside this, you never called one of the functions.

    So here is a working example:

    #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");
      }
    }
    

    Output:

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