Bitfields. Why is there no output?

74 views Asked by At
#include <iostream>
using namespace std;
struct bitfield
{
    unsigned char a : 3, b : 3;
};

int main()
{
    bitfield bf;
    bf.a = 7;
    cout << bf.a;   
    char c;
    cin >> c;
    return 0;
}

I am using VC++ with its latest compiler. When i type cast bf.a to int it gives the desired output (7). But when i dont type cast it, it gives no output and gives no errors. Why is it so?

3

There are 3 answers

0
wally On BEST ANSWER

When i type cast bf.a to int it gives the desired output (7). But when i dont type cast it, it gives no output and gives no errors. Why is it so?

The character (number 7) was written to the console. Character 7 is the bell character.


So you can't see it, but you can hear it. Or rather I could hear the notification sound on Windows 10 when I ran the program.

The same output is generated with:

cout << '\a';

The bell is part of a group of characters that can be referenced with escape sequences.


Note that in this case the use of a char bitfield is not guaranteed by the standard. See here for a question regarding the use of char bitfields.

0
François Andrieux On

You are printing the character who's value is 7. Others have pointed out that this is a special character that is usually not displayed. Cast your value to int or another non-char integer type to display the value, rather than the character. Go look at the ascii table and you'll see character 7 is BEL (bell).

#include <iostream>
using namespace std;
struct bitfield
{
    unsigned char a : 3, b : 3;
};

int main()
{
    bitfield bf;
    bf.a = 7;
    cout << (int)bf.a; // Added (int) here
    char c;
    cin >> c;
    return 0;
}

Edit 1: Since bf.a is only 3 bits, it cannot be set to any displayable character values. If you increase it's size, you can display characters. Setting it to 46 gives the period character.

#include <iostream>
using namespace std;
struct bitfield
{
    unsigned char a : 6, b : 2;
};

int main()
{
    bitfield bf;
    bf.a = 46;
    cout << bf.a;   
    char c;
    cin >> c;
    return 0;
}

Edit 2: See This answer about using bitfields and char.

0
Barath Ravikumar On

Char type bitfield is not supported.

Bitfield declaration supports only 4 identifiers,

  • unsigned int
  • signed int
  • int
  • bool

Source