. Advertisement .
..3..
. Advertisement .
..4..
I’m building a new program, but when I run it, an error pops up. The error displayed is as follows:
error: lvalue required as unary '&' operand
I have tried several workarounds, but they still do not get the desired results. If you have come across this situation and have a solution for the “lvalue required as unary ‘&’ operand” problem, please let me know. Here is what I do:
strftime(AppTime, sizeof(AppTime),"%Y/%m/%d %T", localtime(&((long)u32_Time)));
Thanks!
The cause: The address-operator
&
requires a variable from which to get the address. Your cast(long)u32 Time
produces a temporary that does not necessarily reside in memory and so it has no address that can be accessed. Then it was an imprecise unusual extension if that code ever compiled someplace.The standard extension, §5.3.1,3 requests:
Solution:
Because
std::localtime
requires a pointer to astd::time_t
, you should give one. Casting a C-cast is not portable, and casting tolong
is much less portable.It may be sufficient to use
std::time_t
on your current platform if and only if thestd::time_t
on your current platform is also an unsigned 32 bit type with the same representation as youru32 Time
.Keeping the value in the correct data type first would be more usable:
It is probably better to begin with the error. An “lvalue”, which is something that appears on either side of an equals sign, is a value. This means that the argument you make to the “address operator” (&) must be something you can assign to. This is not syntactically correct in your case.
This restriction is due to the fact that the & operator returns an address for something that is stored somewhere. (long)u32_Time doesn’t exist, but u32_Time does.
It might have worked on more tolerant compilers, as it would allocate space for the long representation u32_Time, and then give you an indication to that. However, I doubt that this will work (as you can see in Linux Server release 6.1).
You can fix this by creating a new variable, and taking its address instead.
But that’s not perfect. Localtime expects a pointer to time_t, not a long pointer. While they may be identical on your platform, it’s better to have: