edited by
2,479 views
2 votes
2 votes
#include<stdio.h>

void main(){

m();

void m(){
    printf("hi\n");

   }
}

 

please explain ?

edited by

3 Answers

Best answer
4 votes
4 votes

Nested function is not supported in standard C i.e. ANSI C but supported in GCC with the help of an extension.

Nested function behaves as local variables and you can not call them before defining function body.

more on nested function : https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

http://stackoverflow.com/questions/2608158/nested-function-in-c

If no function prototype is declared before using it, here the compiler guesses or implicitly creates one depending on the arguments passed with return type as 'int'. If later we declare with same function name and if it does not match with the guessed one (by the compiler) then, compilers throws error. Warning type conflict because of the implicit 'int'.

But calling m() after defining works fine :

selected by
1 votes
1 votes

hello @indrajeet,

Given code is 

  1. #include<stdio.h>
  2. void main(){
  3. m();
  4. void m(){
  5.       printf("hi\n");
  6.    }
  7. }

Let us analyse the code:

  • We are calling function m() at line 3.
  • We have NOT declared or defined a function m(); in previous lines.
  • So by default, compiler will assume that there will be a function in below lines with return type "int".  
  • But at line 4, compiler sees a function definition of m() with return type void. It causes type mismatch.

Hence compiler throws an error.

 

 

0 votes
0 votes
while running this program i have received the following error:

prog.cpp:4:11: error: '::main' must return 'int'
 void main(){
           ^
prog.cpp: In function 'int main()':
prog.cpp:6:3: error: 'm' was not declared in this scope
 m();

ie., if you use the void method it should return some value
   ^
prog.cpp:8:9: error: a function-definition is not allowed here before '{' token
 void m(){
         ^

Related questions

2 votes
2 votes
1 answer
1
indrajeet asked Jul 19, 2016
4,057 views
int main(){ int i=5,j; j=++i + ++i + ++i; printf("%d %d",i,j); return 0; } https://gateoverflow.in/?qa=blob&qa_blobid=15560219953750733487please explain how j = 22 comes ...
0 votes
0 votes
1 answer
4
Desert_Warrior asked May 16, 2016
2,354 views
#include<stdio.h int main() { int a = 5; int b = ++a * a++; printf("%d ",b); return 0; }(a) 25 (b) 30 (c) 36 (d) Undefined Behavior