Hello, my name is Carol. I'm currently taking an introductory course in C++ and we just learned about functions. I was wondering about the standard accepted format for placing function definitions. For instance, in the following program, should I have defined the power function before the int main function instead of after it as I did?

#include <iostream>
#include <cmath>
#include <iomanip>
//function base and the power
//2 as the base raised to the third power
using namespace std;
float power(float,float); //function declaration

int main()
{
    float base;
    float exp;
    float answer;

    cout << "This program finds the base raise to an exponent." << endl;
    cout << "Please input the base number." << endl;
    cin >> base;
    cout << "Please input the exponent." << endl;
    cin >> exp;
    answer = power(base,exp); //function call
    cout << fixed << setprecision(2); //# of decimal places
    cout << "The base is " << base << endl;
    cout << "Raised to the " << exp << " power" << endl;
    cout << "It is equal to " << answer << endl;

    system("pause");
    return 0;
}

float power(float bas, float expo) //function definition
{
      return pow(bas,expo);
}

Both are acceptable, but take note that this only applies to when both the declaration and definition are in the same file. Once you start modularizing your files, the accepted format is a header with the declarations, an implementation file, and one or more usage files:

Header
#ifndef MY_HEADER_H
#define MY_HEADER_H

float power(float,float); //function declaration

#endif
Implementation
#include <cmath>
#include "my_header.h"

float power(float bas, float expo) //function definition
{
      return std::pow(bas, expo);
}
Usage
#include <iostream>
#include <iomanip>
#include "my_header.h"

using namespace std;

int main()
{
    float base;
    float exp;
    float answer;

    cout << "This program finds the base raise to an exponent." << endl;
    cout << "Please input the base number." << endl;
    cin >> base;

    cout << "Please input the exponent." << endl;
    cin >> exp;

    answer = power(base,exp); //function call

    cout << fixed << setprecision(2); //# of decimal places
    cout << "The base is " << base << endl;
    cout << "Raised to the " << exp << " power" << endl;
    cout << "It is equal to " << answer << endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.