Here is a code

#include<stdio.h>
int main(void)
{
  
int a;
a=f(10,3.14);
printf("%d",a);
}
int f(int aa,float bb)
{
	return (aa+bb);
}

If I run the code it produces garbage value, but if I declare the prototype of the function before main it produces the correct output as 13. Why is this so coz without the prototype it's assuming returning int, so in effect it shouldn't have any problem?

if you define the function after it is called by the code -- such as in "main()" -- the compiler needs a prototype to know how to handle the function when it runs across it in the code. otherwise, it has no clue what the function is and whether or not you've called it correctly.

IIRC, older (pre-ANSI) C compilers typically assumed a default of 'int' for return value, but newer compilers do not have to do so.

Basically it comes down to this: If you don't either (1) prototype the function or (2) fully define the function prior to its use, you will be setting yourself up for a variety of potential problems.

.

One method is to have order your instructions call functions above it, so main() would always be the last function!

#include<stdio.h>

int f(int aa,float bb)
{
  return (aa+bb);
}


int main(void)
{
   int a;  
  a=f(10,3.14);
  printf("%d",a);
}

Basically it comes down to this: If you don't either (1) prototype the function or (2) fully define the function prior to its use

Simplify, my friend. :) A function definition is also a prototype, so you don't need to split them up. As long as there is a prototype before the first use, you are safe. If there is an old style declaration or no a declaration at all before the first use, you are not so safe.

Yes, you don't need to write a prototype before function in which it is called (usually in main) but it's common to do like this:
-function prototypes
-main
-function definition...
that is because if you have a lot of functions it's easier to read and understand code, find mistakes... correct me if i'm wrong...sorry if i made some spelling mistakes....:)

Comments
not helpful.

A function definition is also a prototype, so you don't need to split them up

i'm glad you find it so exciting to point out that a function definition, by definition, includes the prototype.
but i'm explaining a basic concept to an inexperienced user here, not defending a dissertation to the pedantic professor.

the point remains : either place a prototype ahead of the first use, or define the function entirely ahead of the first use.


.

This article has been dead for over six months. Start a new discussion instead.