Structures as Function Arguments

  1. A function can have call-by-value and/or call-by-reference parameters of a structure type.

  2. //Program to demonstrate the CDAccount structure type.
    //The example also includes a function that has a call-by-reference parameter
    //with the structure type CDAccount
    #include <iostream>

    //Structure for a bank certificate of deposit:
    struct CDAccount
    {
        double balance;
        double interest_rate;
        int term;   //months until maturity
    };


    void get_data(CDAccount& the_account);
    //Precondition: the_account must have been declared.
    //Postcondition: the_account.balance and the_account.interest_rate
    //have been given values that the user entered at the keyboard.

    int main( )
    {
        CDAccount account;
        get_data(account);

        double rate_fraction, interest;
        rate_fraction = account.interest_rate/100.0;
        interest = account.balance*rate_fraction*(account.term/12.0);
        account.balance = account.balance + interest;

        cout.setf(ios::fixed);
        cout.setf(ios::showpoint);
        cout.precision(2);
        cout << "When your CD matures in "
           << account.term << " months,\n"
           << "it will have a balance of $"
           << account.balance << endl;
        return 0;
    }

    //Uses iostream.
    void get_data(CDAccount& the_account)
    {
        cout << "Enter account balance: $";
        cin >> the_account.balance;
        cout << "Enter account interest rate: ";
        cin >> the_account.interest_rate;
        cout << "Enter the number of months until maturity: "
        cin >> the_account.term;
    }

  3. A structure type can also be the type for the value returned by a function. Consider for example the following function definition:

    CDAccount shrink_wrap(double the_balance, double the_rate, int the_term)
    {
       CDAccount temp;
       temp.balance = the_balance;
       temp.interest_rate = the_rate;
       temp.term = the_term;
       return temp; }

    Once the shrink_wrap function is defined, a value can be given to a variable of type CDAccount as shown below:

    CDAccount new_account;
    new_account = shrink_wrap(1000.00, 5.1, 11);

  4. Hierarchical structure can be used. That means that a structure can have member variables that are also structures.

    For example if we have a structure to represent the date:

    struct Date
    {
       int month;
       int day;
       int year;
    };

    We can use it in the definition of another structure PersonInfo:

    struct PersonInfo
    {
       char sex;
       double height;
       int weight;
       Date birthday;
    };

    So if a structure of type PersonInfo is declared:

    PersonInfo person1;

    The year the person was born can be output to the screen as follows:

    cout << person1.birthday.year;