5

I have been trying to understand pointer concepts by writing simple code, and I got an error problem, and it seems like I couldn't solve it or understand it.

#include <stdio.h>

int *foo(void);

int main(void) {
    printf("%d\n", *foo());

    return 0;
}

int *foo(void) {
    static int num = 1;
    ++num;
    return &(++num);

}

Here is the error message.

error: lvalue required as unary ‘&’ operand
  return &(++num);

Function 'foo()' returns a pointer to int, and main is supposed to be print the returned int by using * operator. For static num within foo(), I thought that by putting static qualifier, num is not temporary variable anymore, so '&' can be used to num.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    same question : [Not able to understand error condition wrt lvalues](https://stackoverflow.com/questions/24471063/not-able-to-understand-error-condition-wrt-lvalues/24471125) – Sander De Dycker Jun 24 '19 at 08:58
  • To fix the problem you can change the line to `++num; return &num;` – M.M Jun 24 '19 at 09:31

2 Answers2

11

The result of ++num is the new value, not the variable, so you're trying to take the address of something that is not actually stored anywhere. That's the layman's explanation.

unwind
  • 391,730
  • 64
  • 469
  • 606
7

There is a difference between C and C++ relative to the prefix increment operator ++.

In C the result is the new value of the operand after incrementation. So in this expression &(++num) there is an atttempt to get the address of a temporary object (rvalue).

In C++ the program will be correct because in C++ the result is the updated operand; it is an lvalue.

That is in C the result is a new value while in C++ the result is the updated operand.

So in C you may not for example write

++++++x;

while in C++ this expression

++++++x;

is correct and you may apply the unary operator & to the expression like

&++++++x;

To make the function correct in C you have to separate the applied operators like

int *foo(void) {
    static int num = 1;
    ++num;
    //return &(++num);
    ++num;
    return &num;

}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335