C++ Structures | Find output programs | Set 4

This section contains the C++ find output programs with their explanations on C++ Structures (set 4).
Submitted by Nidhi, on June 17, 2020

Program 1:

#include <iostream>
using namespace std;

struct st {
    unsigned int A : 5;
    unsigned int B : 6;
    unsigned int C : 7;
    unsigned int D : 8;
} S;

int main()
{
    cout << sizeof(S);
    return 0;
}

Output:

4

Explanation:

We compiled this program on a 32-bit based system

The above program is using the concept of bit fields; it is used to optimize the allocation of memory space.

Here, we declared 4 variables in the structure and specified the required bits for each integer. But due to structure padding, it will allocate 4-byte space. Because the block size in the 32bit system is 4 byte.

This, 4 integer variables will take only in 4 bytes. Because the total size of all is less than 32 bits, if it exceeds more than 32 bits then it will allocate one more block of 4 bytes.

unsigned int A:5;
unsigned int B:6;
unsigned int C:7;
unsigned int D:8;

= 5 + 6 + 7 + 8
= 26

26 is less than 32 bits then the structure allocated 4 bytes of memory.

Program 2:

#include <iostream>
using namespace std;

struct st {
} S;

int main()
{
    cout << sizeof(S);
    return 0;
}

Output:

1

Explanation:

In C language, the size of the empty structure is 0, while the size of the empty structure in C++ is 1. Here, it takes 1 byte to distinguish the object of structures.

Program 3:

#include <iostream>
using namespace std;

struct st {
    int A;
    char CH;
};

int main()
{
    struct st s[] = { { 10, 'A' }, { 20, 'B' } };

    int X, Y;

    X = s[0].A + s[0].CH;
    Y = s[1].A + s[1].CH;

    cout << (X * Y);

    return 0;
}

Output:

6450

Explanation:

Here, we declared a structure with two members A and CH.

In the main() function, we created the array of structure and initialized values.

Evaluate the given expression,

X = s[0].A + s[0].CH;
	X = 10 + 'A';
	X = 10 + 65; // ASCII value of 'A' is 65.
	X = 75;
Y = s[1].A + s[1].CH;
	Y = 20 + 'B';
	Y = 20 + 66;
	Y = 86;

Then
	cout<<(X*Y);

The above cout statement will print the multiplication of 75 and 86 that is 6450.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.