Structure and Function | C++ Structure and Function - Learn C++ - C++ Tutorial - C++ programming




 c++-structure-and-function

Learn c++ - c++ tutorial - c++-structure-and-function - c++ examples - c++ programs

Structure And Function in C++

  • Structure is a collection of variables under a single variable.
  • Structure variables can be passed to a function and returned in a similar way as normal argument.
  • A function is a group of statements that together perform a task.
  • learn c++ tutorials - structure and functions

    learn c++ tutorials - structure and functions Example

  • Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions.
Learn C++ , C++ Tutorial , C++ programming - C++ Language -Cplusplus

Passing structure to function in C++

 pass return object c++
  • A structure variable can be passed to a function in similar way as normal argument.
  • When an element of a structure is passed to a function, you are actually passing the values of that element to the function. Therefore, it is just like passing a simple variable (unless, of course, that element is complex such as an array of character). Consider this example:

Example 1: C++ Structure and Function

#include <iostream> 
using namespace std;

struct Person
{
    char name[50];
    int age;
    float salary;
};

void displayData(Person);   // Function declaration

int main()
{
    Person p;

    cout << "Enter Full name: ";
    cin.get(p.name, 50);
    cout << "Enter age: ";
    cin >> p.age;
    cout << "Enter salary: ";
    cin >> p.salary;

    // Function call with structure variable as an argument
    displayData(p);

    return 0;
}

void displayData(Person p)
{
    cout << "\nDisplaying Information." << endl;
    cout << "Name: " << p.name << endl;
    cout <<"Age: " << p.age << endl;
    cout << "Salary: " << p.salary;
}

Output

Enter Full name: Bill Jobs
Enter age: 55
Enter salary: 34233.4 

Displaying Information. 
Name: Bill Jobs
Age: 55
Salary: 34233.4
  • In this program, user is asked to enter the name, age and salary of a Person inside main() function.
  • Then, the structure variable p is to passed to a function using.
displayData(p);
  • The return type of displayData() is void and a single argument of type structure Person is passed.
  • Then the members of structure p are displayed from this function.

Related Searches to Structure and Function | C++ Structure and Function