How to use a constant value in a function after getting input from user

906 views Asked by At

So here I have a part of my code where I define macros to set the identifier MIN_BIT to a value based on user input:

#define MIN_BITS(n) 1*n
int MIN_BIT = MIN_BITS(n);

And then I take user input for the value of 'n' in the main function.

Now, I have a function to take LSB, arrange it in an array, and print the array in reverse order so MSB is on the left:

void print_binary( unsigned number )
{
    unsigned bits [ MIN_BIT ] ; // <-- error here
    int count = 0 ;
    while( number>0 || count < MIN_BIT )
    {
        bits [count] = number % 2;
        number >>= 1;
        count++;
    }
    for( int i = count -1; i >=0; i--)
        cout << bits[i];
}

However, on the line marked 1 in the above code, I get an error "expression must have a constant value". The value of variable MIN_BIT cannot be used as a constant.

Please suggest a workaround for the issue, or a way to implement this differently.

1

There are 1 answers

5
Remy Lebeau On BEST ANSWER

Try this instead:

#define MIN_BITS(t) (sizeof(t) * 8)

Or, use CHAR_BIT if you need to support systems where a byte is not 8 bits in size:

#define MIN_BITS(t) (sizeof(t) * CHAR_BIT)

Then, you can do this:

void print_binary( unsigned number )
{
    const int num_bits = MIN_BITS(number);

    unsigned bits [ num_bits ];
    int count;

    for(count = 0; (number != 0) && (count < num_bits); ++count)
    {
        bits[count] = number & 1;
        number >>= 1;
    }

    for(int i = count-1; i >= 0; --i)
        cout << bits[i];
}

Live demo


You can't define a static fixed-length array using a value determined at runtime (that is known as a Variable Length Array, which is non-standard and only a few compilers implement it as an extra feature). If you need that, use std::vector instead:

#include <vector>

void print_binary( unsigned number )
{
    std::vector<unsigned> bits;
    bits.reserve(n);

    for(int i = 0; (number != 0) && (i < n); ++i)
    {
        bits.push_back(number & 1);
        number >>= 1;
    }

    for(int i = bits.size()-1; i >= 0; --i)
        cout << bits[i];
}

Otherwise, just define the array to be as large as the maximum bits that the input variable can physically hold, and then use the user entered value to limit how many values you can store in the array:

#define MAX_BITS(t) (sizeof(t) * CHAR_BIT)

void print_binary( unsigned number )
{
    const int max_bits = MAX_BITS(number);

    unsigned bits [ max_bits ];
    int count;

    for(count = 0; (number != 0) && (count < n) && (count < max_bits); ++count)
    {
        bits[count] = number & 1;
        number >>= 1;
    }

    for(int i = count-1; i >= 0; --i)
        cout << bits[i];
}