Error: taking address of rvalue [-fpermissive]

Error: taking address of rvalue [-fpermissive]

This error message occurs when you try to take the address of a temporary or non-lvalue expression in C++.

Here, an rvalue refers to a temporary value or an expression that does not have a memory address.

Let’s see an example to illustrate this error:

    
int* getAddress() {
  int value = 10;
  return &value; // Error: taking address of temporary or non-lvalue
}

int main() {
  int* ptr = getAddress();
  return 0;
}
    
  

In the above example, the function getAddress() attempts to return the address of a local variable value.
However, value is a temporary variable that ceases to exist once the function returns, making its address invalid.

This results in the compiler generating the error: taking address of rvalue [-fpermissive].

To fix this error, you should avoid taking the address of temporary or non-lvalue expressions. Instead, consider using pointers or references to store or manipulate values.
Here’s an updated version of the previous example, demonstrating a correct usage:

    
int value = 10; // Define value outside the function

int* getAddress() {
  return &value; // OK: returning address of a global variable
}

int main() {
  int* ptr = getAddress();
  return 0;
}
    
  

In this updated example, value is declared as a global variable outside the function. Now, the function getAddress() can return the address of this global variable without any issues.

Read more interesting post

Leave a comment