Dealing with a pointer to a bitset in C++

271 Views Asked by At

I have a bunch of bitsets<32> as global variables in my program and I want to update them after passing a pointer to one of them to a function.

Here is an example:

#include<bits/stdc++.h>
using namespace std; 
bitset<32> zero(0); 
bitset<32> ra(0); 
bitset<32> sp; 
bitset<32> gp; 
bitset<32> tp(0); 
bitset<32> t0(0); 
bitset<32> t1(0); 
void LUI(bitset<32>*rd, int imm){
    bitset<32> temp(imm); 
    for(int i=31; i>=12; i--){
        *rd[i]=temp[i];
    }
    for(int i=11; i>=0; i--){
        *rd[i]=0; 
    }
}

How can I update for example t1 through the function LUI() as dereferencing is not working? Here are the errors I get:

error: no match for 'operator*' (operand type is 'std::bitset<32>')
   46 |         *rd[i]=0;
 note:   candidate expects 2 arguments, 1 provided
   46 |         *rd[i]=0;
2

There are 2 best solutions below

0
Vlad from Moscow On BEST ANSWER

The function LUI as is does not make sense. I suppose it is only provided as an example of using the subscript operator with bitsets. Nevertheless you could pass to the function bitsets by reference instead of passing them through pointers

void LUI(bitset<32> &rd, int imm);

As for your problem then instead of

*rd[i]=temp[i];

or

*rd[i]=0;

you have to write

( *rd )[i]=temp[i];

( *rd )[i]=0;

or

rd->operator []( i ) = temp[i];
rd->operator []( i ) = 0;

The problem with your code is that the subscript operator has a higher priority than the dereferencing operator.

4
EliSauder On

Just to elaborate a bit upon comments and the other answer for the question.

To directly solve your issue with no other changes, you need to wrap your de-reference in parenthesis like this: (*rd)[i]. As for why you need to do this, it comes down to operator precedence (https://en.cppreference.com/w/cpp/language/operator_precedence) in cpp, [] (subscript) is evaluated before * indirection (de-referencing), as this is the case, you need to explicitly tell the compiler what you want to do first since otherwise you are directly calling the subscript operator on a pointer which is just an integer.

A recommendation that was made in the comments is to not use <bits/stdc++.h>. You only really want to use this if you are doing something like competitive programming as it is not part of the cpp standard; when using this you are not guaranteed to have it work on all or any compilers other than gcc.
An additional issue is that including unnecessary headers can slow down compiling.

A personal recommendation (and mentioned in the other answer) is to not use pointers, instead think about using references instead of pointers, this will remove any operator precedence issue while still gaining the ability to not copy memory. Here is the function with references:

void LUI(bitset<32>& rd, int imm) {
    bitset<32> temp(imm); 
    for(int i=31; i>=12; i--){
        rd[i]=temp[i];
    }
    for(int i=11; i>=0; i--){
        rd[i]=0; 
    }
}