Search code examples
cfunctionidecs50function-definition

C error: function definition is not allowed here, i already put function above int main(void), erased brackets, error still persists


I'm trying to solve this CS50 Problem titled Credit and I'm new to coding so I really appreciate if you'll help me find what I typed wrong here. Im trying to count the digits of a number prompted from the user, and i keep receiving this error after compiling. The error says ab.c:20:5: error: function definition is not allowed here. Thank u for answering!

#include <stdio.h>
#include <cs50.h>

int get_number_digits(long x);
int main(void)

{

    //Prompt for input
    long digits = get_long("Card Number: \n");

    //Count the digits 
    int count = get_number_digits(digits);
    


    //Function for getting number of digits
    int get_number_digits(long x)
    {
         int number;
         for (number = 0; x > 0; number++)
      {
         x = x / 10;
      }
    }
}

Solution

  • Nested functions are not part of standard C. However they may work depending on the compiler you use. So better to put the get_number_digits function outside main.

    And You forgot to put the return statement in the get_number_digits function.

    #include <stdio.h>
    #include <cs50.h>
    
    int get_number_digits(long x);
    int main(void)
    
    {
    
        //Prompt for input
        long digits = get_long("Card Number: \n");
    
        //Count the digits 
        int count = get_number_digits(digits);
    
    }
    
    //Function for getting number of digits
    int get_number_digits(long x)
    {
         int number;
         for (number = 0; x > 0; number++)
      {
         x = x / 10;
      }
      return number;
    }