Reputation: 59
I am new beginner in the programming world and while I was coding on Functions in C, I came to know that there are three most important parts of the functions namely-
But, while I was solving a problem on factorials of a number I came to know in my code that when I am not including function declaration or function protocol in my code above main() then still the code is running and giving the output as 120. So my question is why a function declaration or function prototype is not affecting the output of my program or is it not necessary to include function declaration or prototype above main().
-------Code-----
#include<stdio.h>
#include<conio.h>
// int fact(int);
main()
{
int x;
x=fact(5);
printf("The factorial is =%d",x);
}
int fact(int n)
{
int f=1,i;
for(I=1;i<=n;i++)
f=f*I;
return (f);
}
Upvotes: 0
Views: 56
Reputation: 223768
If you use a function without declaring it, the compiler may provide a default declaration. This is not part of modern C, but compilers may use old standards or be unduly lax in this regard. (It is better to require explicit declarations because it helps reduce mistakes.)
Any declaration of a function must match the definition of the function. The declaration gives the compiler information about how to call the function. If the declaration does not match, things can go wrong. So, yes, the declaration can affect your program; it can break it.
In this case, you got lucky, the default declaration of a function happened to match your function fact
. The default declaration is a function that returns int
and accepts whatever arguments you pass it, subject to default argument promotions. (Roughly speaking, the default argument promotions are that integers narrower than an int
are converted to int
, and float
values are converted to double
. So, if a function returns int
and accepts only int
and double
arguments, it can match the default declaration.)
A good compiler will warn you that a declaration is missing or that a declaration is wrong. Your compiler has “switches” or other options that tell it what sorts of warning and error messages you want. You should ask for lots of warning messages.
Your compiler probably also has switches that say which version of C to use. (There have been several standard versions, most recently 1999 and 2011, and there are some non-standard variants.) You might want to request that your compiler use the C 2011 standard, until you have good reason to change that. (Unfortunately, if you are using Microsoft Visual C, I do not believe it supports C 2011.)
Upvotes: 4