Creating a struct element

To define the struct, we utilise the struct keyword.

The fundamental syntax for declaring a struct is,

struct structure_name
{
    //structure_elements
} structure_variable;

Here’s one example of how a struct is defined and used in main as a user-defined data type.

#include <iostream>
using namespace std;
 
struct employee
{
    /* data */
    int eId;
    char favChar;
    int salary;
};
 
int main()
{
    struct employee Roy;
    return 0;
}

Accessing struct elements

The dot operator is used to access any of the values of a structure’s members (.). This dot operator is placed between the name of the structure variable and the name of the structure member that we want to access.

There must always be an already defined structure variable before the dot operator and a valid structure element after the dot operator.

Here’s an example of how we can access struct elements.

#include <iostream>
using namespace std;
 
struct employee
{
    /* data */
    int eId;
    char favChar;
    int salary;
};
 
int main()
{
    struct employee Roy;
    Roy.eId = 1;
    Roy.favChar = 'c';
    Roy.salary = 120000000;
    cout << "eID of Roy is " << Roy.eId << endl;
    cout << "favChar of Roy is " << Roy.favChar << endl;
    cout << "salary of Roy is " << Roy.salary << endl;
    return 0;
}

Output:

Output:
eID of Roy is 1
favChar of Roy is c
salary of Roy is 120000000
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in