Pass structures to a function in C++:
Structures are used to group different types of variables in C++. We can use structures to hold data and also we can pass any structure data to a function. In this tutorial, we will learn how to pass data in structures to a function in C++.
C++ program to pass data in structure as arguments to a function:
Let’s take a look at the below program:
#include <iostream>
using namespace std;
struct User
{
string userName;
int age;
};
void printUserInfo(User user)
{
cout << "User name: " << user.userName << ", age: " << user.age << endl;
}
int main()
{
User user;
cout << "Enter the name of the user: " << endl;
cin >> user.userName;
cout << "Enter the age of the user: " << endl;
cin >> user.age;
printUserInfo(user);
}
Here,
- User is a structure to hold one string for user name and one int to hold the age.
- In the main method, we are creating one User object to hold the user data.
- Using cout and cin, we are reading the user data and storing it in user.
- The last line is passing the user data to printUserInfo and this function is printing the values in the user object.
It will give the below output:
Enter the name of the user:
alex
Enter the age of the user:
20
User name: alex, age: 20
Compilation error:
We need to declare the structure before the function always. Otherwise, it will throw a compilation error.
#include <iostream>
using namespace std;
void printUserInfo(User user)
{
cout << "User name: " << user.userName << ", age: " << user.age << endl;
}
struct User
{
string userName;
int age;
};
int main()
{
User user;
cout << "Enter the name of the user: " << endl;
cin >> user.userName;
cout << "Enter the age of the user: " << endl;
cin >> user.age;
printUserInfo(user);
}
It will throw an error:
error: unknown type name 'User'
You might also like:
- C++ how to find the smallest of three numbers
- C++ program to find the total number of characters in a string
- C++ isblank function explanation with example
- C++ program to check if a character is a punctuation using ispunct
- C++ program to check if a character is a hexadecimal using isxdigit
- C++ check if a character is alphabetic using isalpha