C++ Structure and Function

Structures can be combined with functions in C++ to produce more intricate and well-organized programs. A structure-function is a function that accepts a structure as an input.

Synatx:

struct structName {
   dataType member1;
   dataType member2;
   .
   .
   .
   dataType memberN;
};

// structure function
returnType functionName(struct structName parameterName) {
   // function body
}

Example:

#include <iostream>
#include <string>
using namespace std;

struct Person {
   string name;
   int age;
   double height;
};

void display(Person p) {
   cout << "Name: " << p.name << endl;
   cout << "Age: " << p.age << endl;
   cout << "Height: " << p.height << endl;
}

int main() {
   Person john;
   john.name = "John Doe";
   john.age = 35;
   john.height = 6.2;

   display(john);

   return 0;
}

Output:

Name: John Doe
Age: 35
Height: 6.2

The members of the Person structure in this example are name, age, and height. A Person structure is passed as an argument to the show function, which prints out each member. A Person structure named John is constructed and given some initial values in the main method. John is passed as a parameter when calling the display function, which prints the values of John’s members.