Error lvalue required as unary operand

While compiling (with Linux Server release 6.1) strftime(AppTime, sizeof(AppTime),"%Y/%m/%d %T", localtime(&((long)u32_Time))); getting error "error: lvalue required as unary '&' operand...

It’s probably best to start with what the error means. An «lvalue» is something that appears on the left side of an equals sign. What it means is that your argument to the «address of» operator (&) must be something that you could assign to. In your case, this isn’t syntactically correct:

(long)u32_Time = 0;

The reason for this restriction is that the & operator returns the address of something that is stored somewhere. (long)u32_Time isn’t stored somewhere, but u32_Time is.

This might have worked ok on more tolerant compilers because it would allocate some space for the long representation of u32_Time and then give you a pointer to that, but I wouldn’t count on that working (as can be seen in Linux Server release 6.1).

To fix this, you can just create a new variable and take it’s address instead:

long long_Time = (long)u32_Time;
strftime(AppTime, sizeof(AppTime),"%Y/%m/%d %T", localtime(&long_Time));

However, that’s still not perfect. localtime expects a time_t pointer, not a long pointer, and while they might be the same on your platform, you’d be better off with:

time_t time_t_Time = (time_t)u32_Time;
strftime(AppTime, sizeof(AppTime),"%Y/%m/%d %T", localtime(&time_t_Time));

I have the following lines of code :

#define PORT 9987

and

char *ptr = (char *)&PORT;

This seems to work in my server code. But as I wrote it in my client code, it gives this error message :

lvalue required as unary ‘&’ operand

What am I doing wrong?

user207421's user avatar

asked May 24, 2013 at 3:47

Indradhanush Gupta's user avatar

13

C preprocessor is at play here. After the code is preprocessed, this how it looks like.

char *ptr = (char *)&9987;

address of (&) operator can be applied to a variable and not a literal.

answered May 24, 2013 at 3:51

Lazylabs's user avatar

The preprocessor macros have no memory and at compile time the macro is replaced with the value. So actualy thing happening here is char *ptr = (char *)&9987;, which is not possible.

answered May 24, 2013 at 3:54

akhil's user avatar

akhilakhil

7323 silver badges13 bronze badges

3

c++ - error: lvalue required as unary & operand

The address-operator & requires a variable to take the address from. The result of your cast (long)u32_Time is a temporary that does not necessarily reside in memory and therefore has no address that could be taken. So if that piece of code ever compiled somewhere it was a nonstandard compiler extension.

The standard, §5.3.1,3 demands:

The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue […]

How to fix this:
std::localtime expects a pointer to a std::time_t so you best provide that. You did not provide any explanation or further code, so I can only guess that u32_Time is some 4 byte unsigned arithmetic type that is supposed to represent a time in some manner. How that is properly converted into a std::time_t depends on how your compiler implements the latter and how you got the value of the further. Simply applying a C-cast is not portable, and casting to long is even less portable.
If, and only if the std::time_t on your current platform is also a unsigned 32 bit type using the same representation as your u32_Time, it might suffice to use

 localtime(reinterpret_cast<std::time_t*>(&u32_Time));

More portable would be storing the value in the correct data type first:

 std::time_t time = u32_Time;
 localtime(&time);

That way you will get the necessary warnings and/or errors if time_t and the type of u32_Time are not compatible.

I would strongly advice against using C-casts, because once you have to port this piece of code to another platform you will have no means to find that nasty cast easily.

Its probably best to start with what the error means. An lvalue is something that appears on the left side of an equals sign. What it means is that your argument to the address of operator (&) must be something that you could assign to. In your case, this isnt syntactically correct:

(long)u32_Time = 0;

The reason for this restriction is that the & operator returns the address of something that is stored somewhere. (long)u32_Time isnt stored somewhere, but u32_Time is.

This might have worked ok on more tolerant compilers because it would allocate some space for the long representation of u32_Time and then give you a pointer to that, but I wouldnt count on that working (as can be seen in Linux Server release 6.1).

To fix this, you can just create a new variable and take its address instead:

long long_Time = (long)u32_Time;
strftime(AppTime, sizeof(AppTime),%Y/%m/%d %T, localtime(&long_Time));

However, thats still not perfect. localtime expects a time_t pointer, not a long pointer, and while they might be the same on your platform, youd be better off with:

time_t time_t_Time = (time_t)u32_Time;
strftime(AppTime, sizeof(AppTime),%Y/%m/%d %T, localtime(&time_t_Time));

c++ – error: lvalue required as unary & operand

Related posts on c++ :

  • c++ – VS2012 MSVCR120D.dll is missing
  • c++ – InterlockedIncrement usage
  • visual c++ – filling up an array in c++
  • loops – C++ – using glfwGetTime() for a fixed time step
  • c++ – Eigen – get a matrix from a map?
  • c++ error: invalid types int[int] for array subscript
  • c++ – no default constructor exists for class
  • c++ – no matching function to call for getline

Hi. Compiling the code causes the error: lvalue required as unary ‘&’ operand

run_test.py:

from test import test


test()

test.py:

import cython


def test():
    if cython.compiled:
        print("Yep, I'm compiled.")
    else:
        print("Just a lowly interpreted script.")

    a = None
    b = None

    c = (a, b)

    print(c.count(None) in [0, 2])
➜  ~ /usr/local/lib/python2.7.12/bin/cython -2 -X always_allow_keywords=True -D ./test.py                                                                        
➜  ~ /usr/local/bin/gcc -shared -pthread -pipe -fPIC -fwrapv -Wall -fno-strict-aliasing -O2 -I/usr/local/lib/python2.7.12/include/python2.7 -o ./test.so ./test.c
./test.c: In function ‘__pyx_pf_4test_test’:
./test.c:873:67: error: lvalue required as unary ‘&’ operand
                     (*(__Pyx_PyCFunctionFast)(cfunc)->func)(self, &arg, 1) :
                                                                   ^
./test.c:1212:15: note: in expansion of macro ‘__Pyx_CallUnboundCMethod1’
   __pyx_t_2 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyTuple_Type_count, __pyx_v_c, Py_None); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 15, __pyx_L1_error)
               ^
./test.c:874:79: error: lvalue required as unary ‘&’ operand
                     (*(__Pyx_PyCFunctionFastWithKeywords)(cfunc)->func)(self, &arg, 1, NULL)) :
                                                                               ^
./test.c:1212:15: note: in expansion of macro ‘__Pyx_CallUnboundCMethod1’
   __pyx_t_2 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyTuple_Type_count, __pyx_v_c, Py_None); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 15, __pyx_L1_error)
               ^
./test.c:876:79: error: lvalue required as unary ‘&’ operand
                     (*(__Pyx_PyCFunctionFastWithKeywords)(cfunc)->func)(self, &arg, 1, NULL) :
                                                                               ^
./test.c:1212:15: note: in expansion of macro ‘__Pyx_CallUnboundCMethod1’
   __pyx_t_2 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyTuple_Type_count, __pyx_v_c, Py_None); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 15, __pyx_L1_error)
               ^

Next modification solves the problem:

import cython


def test():
    if cython.compiled:
        print("Yep, I'm compiled.")
    else:
        print("Just a lowly interpreted script.")

    a = None
    b = None

    c = (a, b)

    d = None
    print(c.count(d) in [0, 2])
➜  ~ /usr/local/lib/python2.7.12/bin/cython -2 -X always_allow_keywords=True -D ./test.py                                                                        
➜  ~ /usr/local/bin/gcc -shared -pthread -pipe -fPIC -fwrapv -Wall -fno-strict-aliasing -O2 -I/usr/local/lib/python2.7.12/include/python2.7 -o ./test.so ./test.c
➜  ~ /usr/local/lib/python2.7.12/bin/python2 ./test_run.py                                
Yep, I'm compiled.
True

Is this correct behavior or a bug present? Thanks.

➜  ~ /usr/local/lib/python2.7.12/bin/cython --version 
Cython version 0.28a0


posted 7 months ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

C++ has gotten a lot more type-safe than it used to be, if recent impressions are any indication. I mostly dropped it when I moved to Java, but I do minor C++ stuff for AVR chip projects theses days.

Technically, in C++,

malloc()

is invoked by operator

new

undercover, but yes, «new» is preferable in C++.

One thing looks wrong to me, though:

If I’m reading this, pi2 is being initialized to be a pointer to a single byte of memory. It doesn’t match the general context and in any case, it’s generally better NOT to malloc in terms of raw bytes. If you want to malloc space for a byte, do this:

or whatever unit type best fits your needs. Note that this

Actually only allows for a string of 11 characters, since the trailing NUL  character needs a character element as well.

To round out on nit-picking on malloc(), be aware that thanks to memory manager overhead and storage alignment, doing a malloc() on a single byte may actually internally consume 8 or more bytes, so it’s better to find alternative storage environments for small objects.

All of this is moot, however, since in the example code, the malloc() effect is overlaid by a subsequent assignment.

but since pi2 is not free()’d, this is a memory leak!!!

I don’t generally declare multiple variables on a single line myself. For anti-bugging reasons I prefer to declare and initialize each variable on its own line. And since I’m really paranoid, I use

const

where applicable. C does contain traces of the old «constants — aren’t, variables — won’t» so common to older languages.

I’m going to be a «small government» candidate. I’ll be the government. Just me. No one else.

Key27

3 / 3 / 0

Регистрация: 02.04.2017

Сообщений: 273

1

27.09.2017, 21:42. Показов 2723. Ответов 1

Метки нет (Все метки)


Пишу по книге Дейтела. Функция вставки в дерево.
Функции из btree_item.cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
BTreeItem::BTreeItem(const Square& square)
{
 m_left = nullptr;
 m_right = nullptr;
 m_square = square;
}
 
void BTreeItem::setLeft(BTreeItem* left)
{
m_left=left;
}
 
void BTreeItem::setRight(BTreeItem* right)
{
m_right=right;
}
BTreeItem* BTreeItem::getLeft()
{
return m_left;
}
 
BTreeItem* BTreeItem::getRight()
{
return m_right;
}

btree_item.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class BTreeItem
{
public:
BTreeItem(const Square& square);
friend std::ostream& operator << (std::ostream& os, const BTreeItem& obj);
 
 
void setLeft(BTreeItem* left); 
void setRight(BTreeItem* right);
BTreeItem* getLeft();
BTreeItem* getRight();
Square getSquare() const;
virtual ~BTreeItem ();
 
 
private:
Square m_square;
BTreeItem* m_left;
BTreeItem* m_right;
};

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void insert_helper(BTreeItem **ptr,const Square& value)
{
    if (*ptr==nullptr)
    {
    *ptr= new BTreeItem(value);
    }
    else 
      if (value<(*ptr)->getSquare())
      insert_helper(&((*ptr)->getLeft()),value);
    else
      if(value>(*ptr)->getSquare())
      insert_helper(&((*ptr)->getRight()),value);
    else
     std::cout<<value<<"Уже есть"<<std::endl;
}
 
void Btree::bstInsert(const Square& square)
{
insert_helper(&m_root,square);
}
Bash
1
2
3
4
5
6
btree.cpp: In function ‘void insert_helper(BTreeItem**, const Square&)’:
btree.cpp:34:37: error: lvalue required as unary ‘&’ operand
    insert_helper(&((*ptr)->getLeft()),value);
                                     ^
btree.cpp:37:38: error: lvalue required as unary ‘&’ operand
    insert_helper(&((*ptr)->getRight()),value);

Добавлено через 10 минут
Была еще такая версия, но она еще хуже работала.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void Btree::bstInsert(const Square& square)
{
BTreeItem* item=m_root;
    if(item == nullptr)
    {
    item = new BTreeItem(square);
    std::cout<< item->getSquare() <<std::endl;
    }
    else
    {
        while(item!=nullptr)
        {
            if(square==(item->getSquare()))
            {
            std::cout<<"!!!!!!!!n"; 
            }
            else if(square>(item->getSquare()))
            {
            item=item->getRight();
            bstInsert(square);          
            }
            else if(square<(item->getSquare()))
            {
            item=item->getLeft();
            bstInsert(square);          
            }
 
        }
    }
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



DU3

284 / 232 / 114

Регистрация: 07.09.2016

Сообщений: 584

27.09.2017, 21:44

2

C++
1
2
3
4
5
if (value<(*ptr)->getSquare())
{
  BTreeItem* left = (*ptr)->getLeft();
  insert_helper(&left,value);
}

для правой части так же. компилябельность восстановится. на счет корректности кода — хз. сами проверяйте.

и я бы вам посоветовал везде и всегда в условных операторах ставить {} вне зависимости от количества кода в условном блоке.



1



Понравилась статья? Поделить с друзьями:
  • Error lua gui forms playerseditorform helpers lua 300 attempt to index a nil value field
  • Error lp011 section placement failed iar
  • Error low level components
  • Error looser throw specifier for virtual
  • Error lookup скачать торрент