0

I have to do a short assignment for my introductory C class, where I have to ask for a number "N" from the user and calculate it's factorial. The requirements were for me to create a function with the prototype long int factorial(int N). I managed to do it, but I'm confused as to why my code is working with a specific change I made. Here is my code:

#include <stdio.h>

long int factorial(int);

int main(void)
{
    int N;
    printf("Enter a number: ");
    scanf("%d", &N);
    printf("The factorial of %d is: %ld", N, factorial(N));

    return 0;
}

long int factorial(int N)
{
    long int result=1 ;
    int i;

    for(i=1; i<=N; i++)
        result = result * i;

    return result;
}

My code at this point didn't work, and would just return the result of N+1 (if I input 5 for example, it would output 6). I was tweaking random things at this point to see what was the problem, and the removal of "void" in my main function fixed it. The problem is, I don't understand why.

#include <stdio.h>

long int factorial(int);

int main()
{
    int N;
    printf("Enter a number: ");
    scanf("%d", &N);
    printf("The factorial of %d is: %ld", N, factorial(N));

    return 0;
}

long int factorial(int N)
{
    long int result=1 ;
    int i;

    for(i=1; i<=N; i++)
        result = result * i;

    return result;
}

Could anyone explain why the removal of void in my code fixed this?

  • 4
    I can't reproduce; the first version of your code works fine with `5` as the input (it outputs 120). I would wonder if you changed something else and forgot about it, or maybe the first test was made with a different source file (maybe the result of forgetting to save your source file in your editor before compiling). Are you able to reproduce the problem if you paste the first version into a brand new file and compile and run it? – Nate Eldredge Sep 22 '21 at 02:28
  • 2
    The first version of your code works for me and passing void should not change your results. – Fang Sep 22 '21 at 02:29
  • 1
    Check this thread for a discussion on empty parameter list https://stackoverflow.com/questions/13950642/why-does-a-function-with-no-parameters-compared-to-the-actual-function-definiti – Zois Tasoulas Sep 22 '21 at 02:32

0 Answers0