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.
Try this instead:
Or, use
CHAR_BIT
if you need to support systems where a byte is not 8 bits in size:Then, you can do this:
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: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: