Function prototype

Hi there

I am reading... (you know the drill same book :D)
in one of the examples they use function prototype inside main();
I never have seen this before, they state that function prototype can be anywhere in code as long as its before a call to function.... but I never have seen this before, just wonder if this is in line "best practise"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// FunctionPrototype.cpp : Defines the entry point for the console application.
//

#include <iostream>


int main()
{
	void intFrac(float, float&, float&); //declaration
	float number, intPart, fracPart;

	do {
		std::cout << "\nEnter a real number: "; // number from user
		std::cin >> number;

		intFrac(number, intPart, fracPart); // find int and frac
		std::cout << "Integer part is " << intPart << ", fraction part is " << fracPart << std::endl; // print them
	} while (number != 0.0); // exit loop on 0.0
	system("pause");
    return 0;
}
//intFrac()
// finds integer and fractional parts of real number
void intFrac(float n, float& intTp, float& fracP)
{
	long temp = static_cast<long>(n); //convert to long
	intTp = static_cast<float>(temp); // back to float
	fracP = n - intTp; // substract integer part
}
I believe function declarations are supposed to be declared outside of main or else the program should not compile.
I tried it works :)
AFAIK, there is no prohibition against including a function prototype within main, or any other function. However IMO, it is not best practice. Functions have global linkage. It makes sense to include the prototypes in the global section of the program where they are easily found.

Consider if you later have another function that wants to call intFrac(), you will have to move the function prototype so that it is visible by the new function.

http://stackoverflow.com/questions/24564842/function-prototypes-in-main-function
Last edited on
is then wise to show this in book that is used to teach C++? as I understand this approach is questionable at best?
I have (very rarely) used local function declarations to locally change a function's default arguments.
Since C++11, my advice is to prefer a closure over that, because a duplicate declaration is error-prone, and closures are more versatile. It may in some cases eliminate overhead involved in creating a call wrapper, maybe allowing a potential micro-optimization - but this is speculation.

Local function declarations can also be used to shadow names in macros. But it's a better idea to name everything you use in a macro fully, unless you're sure of what you're doing.

As AbstractionAnon suggests, I wouldn't call it a "best practice". If anything, it will lead to code duplication, and it's a linker error waiting to happen.
Last edited on
Topic archived. No new replies allowed.