Why does a function that returns int not need a prototype?

6

I tried this program on DevC++ that would call two different types of function, one returning int and one returning char. I'm confused why the int function doesn't need a prototype, while the char one and any other type of function does.

#include <stdio.h>

//int function1();
char function2() ;

int main (){
    int X = function1() ;
    char Y = function2() ;
    
    printf("%d", X) ;
    printf ("%c", Y) ;
    
    return 0 ;
}

int function1(){
    return 100 ;
}

char function2(){
    return 'B' ;
}

The output:

100B

If I remove the prototype for the char function, it results in:

[Error] conflicting types for 'function2'
[Note] previous implicit declaration of 'function2' was here
Share
Improve this question
4
  • Never write functions without prototypes. Functions without prototypes have arguments passed to them differently than functions with prototypes. If you don't understand why you don't need a prototype for a function that returns int, then complexities and potential bugs caused by that difference in how arguments get passed are something you have to avoid. Look up "default argument promotion". – Andrew Henle Apr 18 at 14:19
  • @louisnot That error is because your definition contradicts this implicit declaration. See what happens when you rely on this for a library function and that function actually returns void or a long long. Your compiler won't see a contradiction, and during runtime your stack will get corrupted. You should heed the warnings. – Emanuel P Apr 18 at 14:24
  • @AndrewHenle But no arguments are passed, so that is kind of irrelevant. – Cheatah Apr 18 at 14:33
  • @Cheatah Until arguments are added - then it's critically relevant. – Andrew Henle Apr 18 at 15:51

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue