You are here:

C++/what is the difference between this two?



please, here is a working code that displays the binary bit pattern, byte by byte using a union.


#include <iostream>

#define SIZE     3

using namespace std;

union bits{
     bits(double n);
     void show_bits();
     int d;
     unsigned char c[SIZE];
     bits::bits(double n){
     d = n;
     void bits::show_bits(){
         int i, j;
         for(j=SIZE-1; j>=0; j--)
         cout <<"bit pattern in byte" << j<<":";
         if(i&c[j])cout << "1";
         else cout << "0";
         int main(){
         bits ob(20);
         return 0;

but when i modify the union to a class like this:

class bits{
     bits(double n);
     void show_bits();
     int d;
     unsigned char c[SIZE];

the code still works but doesnt display the real bits in the number 20..

what could be the problem?  

here is a working code that displays the binary bit pattern, byte by byte using a union.

Well, the code assumes that there are only three (significant) bytes in an int, and is therefore not portable. The  number of bytes in an int is implementation dependent and may vary from implementation to implementation. The following would certainly be be more portable:

union bits
    bits( int n );
    void show_bits();
    int d;
    unsigned char c[ sizeof(int) ]; // sizeof(int) == number of bytes in an integer

Also, the constructor of bits should preferably take an int, not a double - you might be subjecting yoursef to a floating point truncation error otherwise.

Your code is also dependant on endianness of the representation of data. We'll ignore it this particular time, but do have a look at

Coming to your actual question, only a union (not a class or struct) will work as expected here. You are trying to interpret an int as a sequence of some number of bytes (as an array of unsigned char). This is only possible if the int and the array occupy the same area of memory.

When creating a struct or a class, each member variable occupies its own seperate space in memory, each member starts at a different area in memory. All of the members of a union start at the same memory address - thius with a union, the int and the array have exactly the same bytes, but not with a class or struct.


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2017 All rights reserved.

[an error occurred while processing this directive]