Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we call functions before defining it?

Tags:

c

function

#include <stdio.h>

void main()

{

    m();

}

void m()

{

    printf("hi");

}

Output

hi

Warnings

main.c:11:10: warning: conflicting types for 'm' [enabled by default]
     void m()
          ^
main.c:7:9: note: previous implicit declaration of 'm' was here
         m();
         ^

Why this program runs successfully even though m() is called before it is defined? And what is the meaning of the warning?

like image 204
Pankaj Mahato Avatar asked Jan 31 '14 18:01

Pankaj Mahato


People also ask

Can you call a function before its defined?

For example: function myFunction() { // do something }; As you can see, the function name ( myFunction ) is declared when the function is created. This means that you can call the function before it is defined.

Can you call a function before it has been defined C?

In C, if a function is called before its declaration, the compiler assumes the return type of the function as int. For example, the following program fails in the compilation.

Can we call a function before defining it in C++?

Now, while creating the object with the help of a constructor, the constructor will get executed and the other function will get executed before main() method. Hence we can easily call the function before the main(). Difference between "int main()" and "int main(void)" in C/C++?

Can we call a function before defining it in JS?

With JavaScript functions, it is possible to call functions before actually writing the code for the function statement and they give a defined output. This property is called hoisting.


1 Answers

C89 allow this by implicitly converting the return type of function and parameter passed to it to int. See here.

But, this is not valid in C99 and later. This has been omitted from the standard. Either you have to declare a prototype for your function or define it before main. See the result here. There is a compile time error in this case.

like image 191
haccks Avatar answered Oct 23 '22 16:10

haccks