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

4th Dec 2019, 6:23 PM
Alex[]
Alex[] - avatar
5 Respostas
+ 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.
4th Dec 2019, 7:25 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 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.
5th Dec 2019, 5:13 PM
John Wells
John Wells - avatar
+ 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.
4th Dec 2019, 7:35 PM
Schindlabua
Schindlabua - avatar
0
There is no such necessity, it is just about preference whether you would like to keep your functions before or after main.
4th Dec 2019, 7:24 PM
Avinesh
Avinesh - avatar
0
Thank you for help. It was enlightening.
4th Dec 2019, 8:03 PM
Alex[]
Alex[] - avatar