C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Find Output of Program (Q.No. 4)
4.
What will be the output of the program in 16 bit platform (Turbo C under DOS) ?
#include<stdio.h>

int main()
{
    struct value
    {
        int bit1:1;
        int bit3:4;
        int bit4:4;
    }bit;
    printf("%d\n", sizeof(bit));
    return 0;
}
1
2
4
9
Answer: Option
Explanation:

Since C is a compiler dependent language, in Turbo C (DOS) the output will be 2, but in GCC (Linux) the output will be 4.

Discussion:
38 comments Page 1 of 4.

Dhruv said:   4 years ago
Total 4+4+1 = 9 bits (not bytes).
1 byte = 8 bits.
So the answer is 2 bytes.
(4)

Shahid said:   5 years ago
9 bits = 2 bytes.

Prakash said:   6 years ago
Actually, this is a bit field program in that, the bit field only accepts the int and char member not a float that's wise giving an error.

Ramya said:   7 years ago
But in bit field we can't apply size of operator.

Then how it is?

Abhishek said:   7 years ago
Thanks @Piyush.

Ramya said:   7 years ago
#include<stdio.h>

int main()
{
struct value
{
int bit1:2;
int bit3:9;
int bit4:6;
int d:1;
}bit;
printf("%d\n", sizeof(bit));
return 0;
}
output:4

How? Please explain.

Niks said:   7 years ago
4 also the correct answer because as mentioned it depends on the compiler.

Chandana said:   7 years ago
Then the answer to given question should be 9 but it is given 2 why?

The amd size of the function returns the number of bytes and it is in bits.

Pranay kantekure said:   8 years ago
Well said @Robert.

Robert said:   8 years ago
To clarify one aspect : run in gcc the following code (remember size of int = 4 bytes = 32 bits).

#include <stdio.h>

int main()
{
struct a
{
int bit1:1;
int bit3:4;
int bit4:4;
}bit;
printf("%d", sizeof(bit));

return 0;
}


* If you do simple math : 1 + 4 + 4 (number of bits afferent for each int variable ) = 9 bits.
* Since we are speaking about a machine that "thinks" in 4 bytes, it will adjust the value of bit structure to the size of 4 bytes.

Run below code to compare :

#include <stdio.h>

int main()
{
struct a
{
int bit1:1;
int bit3:4;
int bit4:4;
int bit5:24;
}bit;
printf("%d", sizeof(bit));

return 0;
}

The number of bits that the structure occupies is exactly 33.
The output of the program will be 8 ( bytes ) why? 32 + 1 = 4 bytes + another 4 bytes ( the machine thinks in its block of memory of 4 bytes ).


Post your comments here:

Your comments will be displayed after verification.