C++ Functions and Structures: A Comprehensive Guide

Classified in Technology

Written at on English with a size of 6.26 KB.

Function Definition

A function definition in C++ consists of the statements that constitute a function. It includes:

  • Name: The identifier of the function.
  • Parameter List: Variables enclosed in parentheses that hold values passed to the function.
  • Body: Statements within curly braces that perform the function's task.
  • Return Type: The data type of the value the function returns (e.g., int, double, void if no value is returned).

Function Header

The function header declares the function. It consists of:

  • Return Type
  • Name
  • Parameter List

For example: void evenOrOdd(int num). Note that there is no semicolon at the end of the header.

Function Return Type

  • If a function returns a value, the return type must be specified (e.g., int main()).
  • If a function doesn't return a value, its return type is void (e.g., void printHeading()).

Calling a Function

To call a function, use the function name followed by parentheses and a semicolon (e.g., printHeading();). When called, the program executes the body of the function. The compiler must know the function's name, return type, number of parameters, and data type of each parameter before it's called. For instance: evenOrOdd(val); (no data type is needed for the argument in the call).

Function Prototype

A function prototype is similar to the header but ends with a semicolon (e.g., void printHeading();). It's placed near the top of the program.

Sending Data into a Function

  • Argument: The actual value passed to the function (also called an actual parameter).
  • Parameter: The variable in the function definition that receives the argument (also called a formal parameter).

You can pass values into a function at the time of call (e.g., c = sqrt(a*a + b*b);). A function can have multiple parameters.

Calling Function with Multiple Arguments Example:


displayData(height, weight);     // call
void displayData(int h, int w)     // heading
{
    cout << "Height = " << h << endl;
    cout << "Weight = " << w << endl;
}

Passing Data by Value

When an argument is passed to a function by value, a copy of its value is placed in the parameter. The function cannot modify the original argument.

Passing Data to Parameters by Value Example:


int val = 5;
evenOrOdd(val);

Returning a Value from a Function

The return statement sends a value back from the function to the part of the program that called it. The prototype and definition must indicate the data type of the return value (not void). The format is return expression;. The expression can be a variable, literal value, or another expression, and it should match the declared return type of the function.

Returning a Boolean Value

Declare the return type in the function prototype and heading as bool.

Boolean Return Example:


bool isValid (int);        // prototype
bool isValid (int val)     // heading
{
    int min = 0, max = 100;
    if (val >= min && val <= max)
        return true;
    else
        return false;
}

if (isValid(score))       // call

Default Arguments

Default arguments are values passed automatically if arguments are missing from the function call. They must be constants declared in the prototype or header (whichever appears first) (e.g., void evenOrOdd(int = 0);). Multi-parameter functions can have default arguments for some or all parameters (e.g., int getSum(int, int = 0, int = 0);). If not all parameters have defaults, those without must be declared first in the parameter list.

Reference Variables

A reference variable is an alias for another variable. It's defined with an ampersand (&) in the prototype and header (e.g., void getDimensions(int&, int&);). Changes to a reference variable directly modify the original variable it refers to. Reference variables are used to implement passing parameters by reference.

Pass by Reference Example:


void squareIt(int &);      // prototype
void squareIt(int &num)
{
    num *= num;
}

int localVar = 5;
squareIt(localVar);      // localVar now contains 25

Structures

A structure in C++ is a user-defined data type that allows you to group multiple variables of different data types together.

Struct Declaration Example:


struct Student
{
    int studentID;
    string name;
    short year;
    double gpa;
};

Defining Structure Variables:

To define structure variables, use the structure tag as the type name. For example: Student s1;

Accessing Structure Members:

Use the dot (.) operator to access individual members of a structure variable.


getline(cin, s1.name);
cin >> s1.studentID;
s1.gpa = 3.75;

Displaying Structure Members:

Display each field separately using the dot operator.


cout << s1.studentID << endl;
cout << s1.name << endl;
cout << s1.gpa;

Using a Constructor to Initialize Structure Members:

A constructor is a special function that initializes objects of a class. The constructor's name must be the same as the structure's name, and it cannot have a return type.


// Example with constructor (not shown in original HTML)
struct Student
{
    int studentID;
    string name;
    short year;
    double gpa;

    // Constructor
    Student(int id, string n, short yr, double g) {
        studentID = id;
        name = n;
        year = yr;
        gpa = g;
    }
};

int main() {
    // Create a Student object using the constructor
    Student s2(12345, "Alice Lee", 2024, 3.9);

    return 0;
}

Entradas relacionadas: