Q:

C++ Structures | Find output programs | Set 4

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ Structures (set 4).

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;
}

Program 2:

#include <iostream>
using namespace std;

struct st {
} S;

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

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;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

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.

Answer Program 2:

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.

Answer Program 3:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Structures | Find output programs | Set 5... >>
<< C++ Structures | Find output programs | Set 3...