-4

I am trying to learn C and was watching this youtube tutorial and had the following query:

At 1:40:24 the function is written below the main function block but the code does not throw an error:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    sayHi();
    return 0;
}

void sayHi() {
    printf("Hello User");
}

At 1:52:00 he runs another function he created below the main block but this time an error comes up, which he explicitly states is due to the function being written below the main block. Why does this error not come up in the first case?

Simson
  • 3,373
  • 2
  • 24
  • 38
Vishal Jain
  • 443
  • 4
  • 17
  • 1
    Please provide the code in your question. – Mickael B. Jan 28 '20 at 20:05
  • 1
    Provide links for reference. Thats a good thing. But the question should be understandable without links. – klutt Jan 28 '20 at 20:08
  • Could you please find the other example from the video for us too and edit the question to include it. This would make the question better. – Simson Jan 29 '20 at 02:03

1 Answers1

2

Calling functions without first declaring them is possible, but is not standard practice and can't be relied upon. In short, it's bad form, and a good compiler would have warned about it. Using GCC, compiling that code gives me the following warning:

$ In function 'main':
$ warning: implicit declaration of function 'sayHi' [-Wimplicit-function-declaration]

When the compiler reaches sayHi(), it will assume it takes no arguments and returns type int as a guess, because it hasn't seen a prototype for that function yet. This guess is called an implicit declaration. The correct way to do this would be to either define the function before it is called:

void sayHi() {
    printf("Hello User");
}

int main()
{
    sayHi();
    return 0;
}

...or to declare it before calling it:

void sayHi();

int main()
{
    sayHi();
    return 0;
}

void sayHi() {
    printf("Hello User");
}