Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a c++ dereference an lvalue or an rvalue?

I am confident I understand the meaning of rvalue and lvalue. What's not clear to me is whether a dereference is an rvalue.

Consider this:

#define GPIO_BASE             0x20200000
#define GPFSEL1               (*(volatile unsigned int *)(AUX_MU_BASE + 0x4))

GPFSEL1 is a dereference to an unsigned int pointer. That unsigned int pointer is a physical address of a hardware register.

I have read that this is a common technique in bare metal programming to access hardware registers directly. So far I am able to use it with no problem.

Now I want a reference to GPFSEL1 as a member of a struct. Is this possible?

struct MotorControl
{
    u8 pwm_pin;
    u8 ctrla_pin;
    u8 ctrlb_pin;
    volatile unsigned int* MYGPFSEL; // this is not the same thing so does not work
}

Given this function below, what's the correct way to reference GPFSEL1 which is defined elsewhere and how to dereference it to set the its value?

MotorContorl group
group.MYGPFSEL = ?
void set(unsigned char pin_number, bool high)
{
if (high)
    {
      // how to correct this statement
      group.MYGPFSEL |= 1<< pin_number;
    } 
}
like image 600
Sam Hammamy Avatar asked Oct 23 '25 16:10

Sam Hammamy


1 Answers

"Dereference" is a verb - you dereference a pointer to get access to the value it points to.

The type conversion is straightforward - if you have a pointer to an integer, and you dereference it, you're now working with an integer. It's an lvalue, as it (by construction) takes up a location in memory, and one that you can (usually) modify.

int x = 10;
int* xptr = &x;
*xptr = 5; // *xptr is an lvalue
std::cout << "X: " << x << std::endl; // Prints 5

However, the pointer needs to point to a place in memory. If you just start with

int* xptr;
*xptr = 5;

You're going to get an error, since you're trying to dereference a pointer that doesn't point to a valid memory address. (And if it does, that's purely by coincidence, and you'll incorrectly change the value.)

If you want a reference to GPFSEL1 as a member of your MotorControl struct, you will not be able to initialize the struct without passing it the object to which it will reference. What you probably want instead is a pointer inside the struct, which is much easier to work with:

MotorControl myMotorControl;
myMotorControl.MYGPFSEL = GPFSELF1;
like image 200
GraphicsMuncher Avatar answered Oct 26 '25 07:10

GraphicsMuncher