Tuesday, 1 April 2014

In C, if a function is called before its declaration, the compiler assumes return type of the function as int.

For example, the following program fails in compilation.

#include <stdio.h>
int main(void)
{
    // Note that func() is not declared
    printf("%d\n", func());
    return 0;
}

char func()
{
   return 'G';
}

The following program compiles and run fine because return type of func() is changed to int.

#include <stdio.h>
int main(void)
{
    printf("%d\n", func());
    return 0;
}

int func()
{
   return 10;
}

What about parameters?
            Compiler assumes nothing about parameters. Therefore, the compiler will not be able to perform compile-time checking of argument types and parity when the function is applied to some arguments. This can cause problems. For example, the following program compiled fine in GCC and produced garbage value as output.

#include <stdio.h>
int main (void)
{
    printf("%d", sum(10, 5));
    return 0;
}
int sum (int b, int c, int a)
{
    return (a+b+c);
}

There is this misconception that the compiler assumes input parameters also int. Had compiler assumed input parameters int, the above program would have failed in compilation.

It is always recommended to declare a function before its use so that we don’t see any surprises when the program is run.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
byteKoding

byteKoding

byteKoding.com is started with an intention to provide every updates related to technology and programming. It is specially for helping people in developing software projects in different programming languages like C/C++, Java, C#.Net, ASP.Net etc. The details that we share here can be very much useful in creating your software a great success.

0 comments