Site icon ucdev

What is function prototype in C

In C language function prototype is just information for the compiler about the existence of a function. It also provides basic information about its name, returning type, and list of accepted arguments. Let’s see it in an example:

#include <stdio.h>

void print_hello_msg(void); // This is prototype for the print_hello_msg function

int main()
{
print_hello_msg();

return 0;
}

void print_hello_msg(void)
{
printf("Hello World");
}

In cases like this one, where the call to the function appears in code before the actual definition, the function prototype is necessary. If we miss it, the behavior of the program may be very random. It may compile with warnings, it may give errors, and may work properly. But also it can happen that it will crash giving very strange output and debugging it will be very hard, so it’s better to not forget about it. But there is a case where it is not needed. Let’s rewrite our code a little bit.

#include <stdio.h>

void print_hello_msg(void)
{
printf("Hello World");
}

int main()
{
print_hello_msg();

return 0;
}

In code written this way, where the actual call to the function print_hello_msg() occurs after the definition, putting function prototype is just optional. You can do it to keep your code clean, but nothing wrong happens when you try to compile it.

As we saw in the given examples, the function prototype looks and works like a function declaration, so are there any differences between them?

Yes, there are few differences:

To sum up, this topic, what is worth remembering is that although function prototype is just information to the compiler, same as function declarations, it’s not. It may, at first sight, look the same but there are some important differences that I explained as simply as possible so don’t forget, these two terms can’t be used interchangeably, as some may think.

References:

Exit mobile version