c++ - Function parameter not an lvalue? -
i'm creating function const int time in seconds , print real time in hours minutes , seconds. localtime can that, returning tm construction time.h. panned this:
bool elapsed(const int timeout) { //cast integer time_t struct tm * = localtime( (time_t&) &timeout); std::wcout<<l"time elapsed: "<<now->tm_hour<<':'<<now->tm_min<<':'<<now->tm_sec<<"\r\n"; homecoming timeout>600; } but throws error: (time_t&)&timeout - look must lvalue
besides troubling me an before consonant, error makes no sense me. i've read lvalues things names. case exception?
the localtime function requires argument of type time_t*, pointer time_t object.
in current code, don't have time_t object, can't create valid pointer such object.
define local time_t object, initialized (converted) value of timeout, , pass object's address localtime:
bool elapsed(const int timeout) { time_t t_timeout = timeout; struct tm * = localtime(&t_timeout); // ... but if possible, cleaner declare timeout parameter time_t in first place:
bool elapsed(time_t timeout) { struct tm * = localtime(&timeout); // ... this assumes timeout value sensible value pass localtime(). isn't. time_t value represents time, not duration; on many systems, it's number of seconds since 1970-01-01 00:00:00 gmt. timeout value of 3600, example, represent 1:00 on jan 1, 1970. localtime name implies, treats local time, depending on time zone might be, example, 4pm on dec 31. , that's assuming mutual interpretation of time_t values; language standard guarantees it's arithmetic type able represent times somehow.
if goal break downwards timeout value hours, minutes, , seconds, arithmetic yourself:
int seconds = timeout % 60; int minutes = timeout / 60; // integer partition truncates int hours = minutes / 60; minutes %= 60; as why got particular error message: reference has refer object. when compile code g++ get:
c.cpp:6:45: error: invalid cast of rvalue look of type 'const int*' type 'time_t& {aka long int&}' an lvalue is, roughly, look refers object. given
int x = 42; the look x value, 42 , x+1 not.
the look timeout lvalue, because it's name of object. look &timeout not lvalue. evaluates value (the address of timeout, of type time_t*), not refer object, because don't have an object of type time_t* refer to.
you can convert (cast) lvalue reference type. since &timeout not lvalue, cast invalid.
but doesn't matter, because converting reference doesn't create sense in context. telling how cast correctly not helpful, since no cast required or appropriate you're trying accomplish. need little simple arithmetic -- no pointers, no references, no casts.
c++ lvalue
No comments:
Post a Comment