0
Why necessity of void swap (int*, int*) before and after main if just one void before its enough in C?
C/ C++ https://code.sololearn.com/cd1U9rEC48j0/?ref=app https://code.sololearn.com/cf0etOkIeoxM/?ref=app
5 Answers
+ 5
The statement defined above, after the header file is known as a function prototype.
In c, the main method is the start of execution, and when we call any function within main, the compiler looks for its return type and type of arguments passed..
Consider, if you haven't defined the function prototype in the beginning, and you have created a function after main, and called it in the main function, the compiler won't know the type of function and its return type.
So in order to make compiler know about the return type and arguments type, we declare function prototype.
If you don't like defining the prototype, you need to define the function along with its body before the main function.
+ 5
There are cases where using prototypes is required. When two functions, have a circular reference. Meaning they both call one another. This sometimes occurs in recursive algorithms. But, for most code it is not needed.
+ 2
It's called a forward declaration. It's not necessary as you said; however, there are a few benefits:
- forward declaring your functions before using them is like having a summary of your code at the top
- You won't accidentally use a function before you defined it and run into an error, because everything is defined at the top
For example, if function a calls function b, and function b calls function a, you create a loop and you cannot possibly define one without the other. In this case you need to forward declare them before you write the function bodies, otherwise you cannot compile the code.
It becomes more relevant once you start splitting programs into multiple files. Header files (.h) will usually contain all the forward declarations and the source files (.c/.cpp) all the definitions.
0
There is no such necessity, it is just about preference whether you would like to keep your functions before or after main.
0
Thank you for help. It was enlightening.