-1

This is my code to generate Pascal's triangle in C language.

#include<stdio.h>
#include<conio.h>

void main()
{
    int i, n, c;
    scanf("%d", &n);
    for (i = 0; i < n; i++)
    {
        for (c = 0; c <= (n - i - 2); c++)
            printf(" ");
        for (c = 0; c <= i; c++)
            printf("%ld", factorial(i) / (factorial(c)*factorial(i - c)));
        printf("\n");
    }
    getche();
}

long factorial(int n)
{
    int c;
    long res = 1;
    for (c = 1; c <= n; c++)
        res = res*c;
    return(res);
}

On compilation it shows two errors:

  • conflicting types for 'factorial'

  • previous implicit declaration of 'factorial' was here

What is my mistake here?

Anton Savin
  • 40,838
  • 8
  • 54
  • 90
shri_wahal
  • 344
  • 1
  • 4
  • 16

2 Answers2

1

conflicting types for 'factorial'
previous implicit declaration of 'factorial' was here

Both errors refers to one thing: The function factorial shall be declared before used.
Simply move the definition before main or write a declaration for it before main.

I'd not write a detailed explanation for you as there're already some, e.g. What is the difference between a definition and a declaration?

Community
  • 1
  • 1
starrify
  • 14,307
  • 5
  • 33
  • 50
0

You are using factorial in main before you define it. This is legal in C, but makes the compiler guess that your function returns an int. However, when reaching the definition of factorial, the compiler notices that it returns, actually, a long, which causes the error.

You can fix this in two ways:

  1. Swap the definitions of main and factorial or

  2. Introduce a forward declaration of factorial before definition of main by adding long factorial(int n);.

jlahd
  • 6,257
  • 1
  • 15
  • 21