0

These code works perfectly:

#include <ctime>


int main()
{
    time_t t;
    struct tm* now;

    t = time(0);          // Here is my attention
    now = localtime(&t);  // and here

    return 0;
}

Now I want to use this as condition in if statement, so I want to do this in one line. I try this code:

now = localtime(&(time(0)));

But I got the error:

E0158 expression must be an lvalue or a function designator

Why I can't call a function inside of another function and use it's result as parameter?

P.S. I'm working in Visual Studio 2017.

Mikhail_Sam
  • 10,602
  • 11
  • 66
  • 102

2 Answers2

0

The term &variable gets you the address of an lvalue. An lvalue is anything that can have a value assigned to it and thereby has a valid memory address. If you think about the return value of a function, you cannot assign to it:

time(0) = 3;

makes no sense. And this is why you can't get it's address. Both time(0) and 3 are rvalue references. All rvalue references, if not captured, are destroyed at the end of the expression, which might be the next semicolon or closing parenthesis.

If you want to define a function that accepts an rvalue reference you'll have to give it the following signature:

void function(int&& param)

Where the && signifies the rvalue reference.

Post Self
  • 1,471
  • 2
  • 14
  • 34
  • _All rvalue references, if not captured, are destroyed at the next semicolon_ That's not entirely correct. It's at the end of expression, which might, or might not, end with a semicolon. – Algirdas Preidžius Aug 16 '17 at 07:57
  • Okay, sure. If it's a closing parenthesis, then it'll end there. I'll fix it – Post Self Aug 16 '17 at 07:58
-1

Please check out this SO answer about lvalues and rvalues, as it provides a more detailed explanation.

But it basically wraps around this:
The & operator takes the address of an object. The result of a function call is a temporary object (an rvalue) which is eventually destroyed after the call (I'm not sure when exactly though).
Taking the address of an rvalue would result in a dangling pointer and is thusly forbidden.

Määäxx
  • 19
  • 1
  • 4