0

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;
      }
    }
}
chris10
  • 33
  • 6
  • as mentioned in https://stackoverflow.com/questions/2608158/nested-function-in-c – ewokx Jul 31 '20 at 09:52
  • @SaiSreenivas I tried doing it but a new error generated error: control reaches end of non-void function – chris10 Jul 31 '20 at 09:54
  • 1
    Does this answer your question? [Nested function in C](https://stackoverflow.com/questions/2608158/nested-function-in-c) – Roy Avidan Jul 31 '20 at 13:11

1 Answers1

1

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;
}
Sai Sreenivas
  • 1,690
  • 1
  • 7
  • 16
  • 1
    I was just comparing it to the previous program i wrote where the function worked wondering what i did wrong now. That's whyyyyyyyy. Thank you so much! Appreciate it – chris10 Jul 31 '20 at 10:01