error non lvalue in assignment

Understanding lvalues and rvalues in C and C++

The terms lvalue and rvalue are not something one runs into often in C/C++ programming, but when one does, it's usually not immediately clear what they mean. The most common place to run into these terms are in compiler error & warning messages. For example, compiling the following with gcc :

True, this code is somewhat perverse and not something you'd write, but the error message mentions lvalue , which is not a term one usually finds in C/C++ tutorials. Another example is compiling this code with g++ :

Now the error is:

Here again, the error mentions some mysterious rvalue . So what do lvalue and rvalue mean in C and C++? This is what I intend to explore in this article.

A simple definition

This section presents an intentionally simplified definition of lvalues and rvalues . The rest of the article will elaborate on this definition.

An lvalue ( locator value ) represents an object that occupies some identifiable location in memory (i.e. has an address).

rvalues are defined by exclusion, by saying that every expression is either an lvalue or an rvalue . Therefore, from the above definition of lvalue , an rvalue is an expression that does not represent an object occupying some identifiable location in memory.

Basic examples

The terms as defined above may appear vague, which is why it's important to see some simple examples right away.

Let's assume we have an integer variable defined and assigned to:

An assignment expects an lvalue as its left operand, and var is an lvalue, because it is an object with an identifiable memory location. On the other hand, the following are invalid:

Neither the constant 4 , nor the expression var + 1 are lvalues (which makes them rvalues). They're not lvalues because both are temporary results of expressions, which don't have an identifiable memory location (i.e. they can just reside in some temporary register for the duration of the computation). Therefore, assigning to them makes no semantic sense - there's nowhere to assign to.

So it should now be clear what the error message in the first code snippet means. foo returns a temporary value which is an rvalue. Attempting to assign to it is an error, so when seeing foo() = 2; the compiler complains that it expected to see an lvalue on the left-hand-side of the assignment statement.

Not all assignments to results of function calls are invalid, however. For example, C++ references make this possible:

Here foo returns a reference, which is an lvalue , so it can be assigned to. Actually, the ability of C++ to return lvalues from functions is important for implementing some overloaded operators. One common example is overloading the brackets operator [] in classes that implement some kind of lookup access. std::map does this:

The assignment mymap[10] works because the non-const overload of std::map::operator[] returns a reference that can be assigned to.

Modifiable lvalues

Initially when lvalues were defined for C, it literally meant "values suitable for left-hand-side of assignment". Later, however, when ISO C added the const keyword, this definition had to be refined. After all:

So a further refinement had to be added. Not all lvalues can be assigned to. Those that can are called modifiable lvalues . Formally, the C99 standard defines modifiable lvalues as:

[...] an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.

Conversions between lvalues and rvalues

Generally speaking, language constructs operating on object values require rvalues as arguments. For example, the binary addition operator '+' takes two rvalues as arguments and returns an rvalue:

As we've seen earlier, a and b are both lvalues. Therefore, in the third line, they undergo an implicit lvalue-to-rvalue conversion . All lvalues that aren't arrays, functions or of incomplete types can be converted thus to rvalues.

What about the other direction? Can rvalues be converted to lvalues? Of course not! This would violate the very nature of an lvalue according to its definition [1] .

This doesn't mean that lvalues can't be produced from rvalues by more explicit means. For example, the unary '*' (dereference) operator takes an rvalue argument but produces an lvalue as a result. Consider this valid code:

Conversely, the unary address-of operator '&' takes an lvalue argument and produces an rvalue:

The ampersand plays another role in C++ - it allows to define reference types. These are called "lvalue references". Non-const lvalue references cannot be assigned rvalues, since that would require an invalid rvalue-to-lvalue conversion:

Constant lvalue references can be assigned rvalues. Since they're constant, the value can't be modified through the reference and hence there's no problem of modifying an rvalue. This makes possible the very common C++ idiom of accepting values by constant references into functions, which avoids unnecessary copying and construction of temporary objects.

CV-qualified rvalues

If we read carefully the portion of the C++ standard discussing lvalue-to-rvalue conversions [2] , we notice it says:

An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue. [...] If T is a non-class type, the type of the rvalue is the cv-unqualified version of T. Otherwise, the type of the rvalue is T.

What is this "cv-unqualified" thing? CV-qualifier is a term used to describe const and volatile type qualifiers.

From section 3.9.3:

Each type which is a cv-unqualified complete or incomplete object type or is void (3.9) has three corresponding cv-qualified versions of its type: a const-qualified version, a volatile-qualified version, and a const-volatile-qualified version. [...] The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements (3.9)

But what has this got to do with rvalues? Well, in C, rvalues never have cv-qualified types. Only lvalues do. In C++, on the other hand, class rvalues can have cv-qualified types, but built-in types (like int ) can't. Consider this example:

The second call in main actually calls the foo () const method of A , because the type returned by cbar is const A , which is distinct from A . This is exactly what's meant by the last sentence in the quote mentioned earlier. Note also that the return value from cbar is an rvalue. So this is an example of a cv-qualified rvalue in action.

Rvalue references (C++11)

Rvalue references and the related concept of move semantics is one of the most powerful new features the C++11 standard introduces to the language. A full discussion of the feature is way beyond the scope of this humble article [3] , but I still want to provide a simple example, because I think it's a good place to demonstrate how an understanding of what lvalues and rvalues are aids our ability to reason about non-trivial language concepts.

I've just spent a good part of this article explaining that one of the main differences between lvalues and rvalues is that lvalues can be modified, and rvalues can't. Well, C++11 adds a crucial twist to this distinction, by allowing us to have references to rvalues and thus modify them, in some special circumstances.

As an example, consider a simplistic implementation of a dynamic "integer vector". I'm showing just the relevant methods here:

So, we have the usual constructor, destructor, copy constructor and copy assignment operator [4] defined, all using a logging function to let us know when they're actually called.

Let's run some simple code, which copies the contents of v1 into v2 :

What this prints is:

Makes sense - this faithfully represents what's going on inside operator= . But suppose that we want to assign some rvalue to v2 :

Although here I just assign a freshly constructed vector, it's just a demonstration of a more general case where some temporary rvalue is being built and then assigned to v2 (this can happen for some function returning a vector, for example). What gets printed now is this:

Ouch, this looks like a lot of work. In particular, it has one extra pair of constructor/destructor calls to create and then destroy the temporary object. And this is a shame, because inside the copy assignment operator, another temporary copy is being created and destroyed. That's extra work, for nothing.

Well, no more. C++11 gives us rvalue references with which we can implement "move semantics", and in particular a "move assignment operator" [5] . Let's add another operator= to Intvec :

The && syntax is the new rvalue reference . It does exactly what it sounds it does - gives us a reference to an rvalue, which is going to be destroyed after the call. We can use this fact to just "steal" the internals of the rvalue - it won't need them anyway! This prints:

What happens here is that our new move assignment operator is invoked since an rvalue gets assigned to v2 . The constructor and destructor calls are still needed for the temporary object that's created by Intvec(33) , but another temporary inside the assignment operator is no longer needed. The operator simply switches the rvalue's internal buffer with its own, arranging it so the rvalue's destructor will release our object's own buffer, which is no longer used. Neat.

I'll just mention once again that this example is only the tip of the iceberg on move semantics and rvalue references. As you can probably guess, it's a complex subject with a lot of special cases and gotchas to consider. My point here was to demonstrate a very interesting application of the difference between lvalues and rvalues in C++. The compiler obviously knows when some entity is an rvalue, and can arrange to invoke the correct constructor at compile time.

One can write a lot of C++ code without being concerned with the issue of rvalues vs. lvalues, dismissing them as weird compiler jargon in certain error messages. However, as this article aimed to show, getting a better grasp of this topic can aid in a deeper understanding of certain C++ code constructs, and make parts of the C++ spec and discussions between language experts more intelligible.

Also, in the new C++ spec this topic becomes even more important, because C++11's introduction of rvalue references and move semantics. To really grok this new feature of the language, a solid understanding of what rvalues and lvalues are becomes crucial.

error non lvalue in assignment

rvalues can be assigned to lvalues explicitly. The lack of implicit conversion means that rvalues cannot be used in places where lvalues are expected.
That's section 4.1 in the new C++11 standard draft.
You can find a lot of material on this topic by simply googling "rvalue references". Some resources I personally found useful: , , and .
This a canonical implementation of a copy assignment operator, from the point of view of exception safety. By using the copy constructor and then the non-throwing , it makes sure that no intermediate state with uninitialized memory can arise if exceptions are thrown.
So now you know why I was keeping referring to my as "copy assignment operator". In C++11, the distinction becomes important.

For comments, please send me an email .

12.3 — Lvalue references

Lvalue references must be bound to a modifiable lvalue.

The Linux Code

Demystifying the "Expression Must Be a Modifiable Lvalue" Error in C++

As C++ developers, we‘ve all likely encountered the dreaded "expression must be a modifiable lvalue" error at some point. This confusing compile-time error can be a roadblock, but if we take the time to truly understand it, it can help us write safer and more robust C++ code overall.

In this comprehensive guide, we‘ll demystify this error completely by looking at what it means, why it happens, how to diagnose it, and best practices to avoid it in the future. Let‘s get started!

What Exactly Does "Expression Must Be a Modifiable Lvalue" Mean in C++?

When the compiler throws this error, it‘s telling us that we tried to assign something to an expression that cannot be assigned to. Let‘s break it down word-by-word:

  • Expression: This refers to any valid C++ expression like a variable, arithmetic operation, function call etc. Basically, any combination of literals, variables, operators and functions that evaluates to a value.
  • Must be: The expression is expected to have a certain property.
  • Modifiable: The property is that the expression can be modified/assigned to.
  • Lvalue: An lvalue refers to an expression that represents a specific memory location. Lvalues have identifiable memory addresses that can be accessed and modified.

Put simply, the error occurs because we tried to assign a value to something that cannot be assigned to. The expression on the left hand side of the assignment operator = needs to be a modifiable lvalue.

This is because the assignment operator stores the rvalue (right hand side expression) at the location in memory represented by the lvalue (left hand side). For this modification of memory to work correctly, the lvalue must refer to a valid modifiable location.

Classifying Expressions as Lvalues and Rvalues

To really understand this error, we need to be clear on the difference between lvalues and rvalues in C++.

Lvalues are expressions that represent identifiable memory locations that can be accessed/modified in some way. Some key properties of lvalues:

  • Have distinct memory addresses that can be accessed directly.
  • Can appear on either side of the assignment operator ( = ).
  • Can be used as operands with unary & address-of operator.
  • Can be modified, if declared without const .

Some examples of lvalues:

  • Named variables like int x;
  • Dereferenced pointers like *ptr
  • Array elements like myArray[5]
  • Member fields like obj.member
  • Function calls that return lvalue references like int& func()

Rvalues are expressions that do not represent identifiable memory locations. They cannot be assigned to. Some examples:

  • Literals like 5 , 3.14 , ‘a‘ etc.
  • Temporary values like those returned by functions
  • Operators applied to operands producing temporary values like x + 5
  • Functions returning non-reference types like int func()

So in summary, lvalues have identifiable memory locations and can appear on the left side of assignments whereas rvalues cannot.

Common Causes of the "Expression Must Be a Modifiable Lvalue" Error

Understanding lvalues vs rvalues, we can now look at some of the most common scenarios that cause this error:

1. Assigning to a Constant/Read-only Variable

When we declare a variable with const , it becomes read-only and its value cannot be changed. Trying to assign to it results in our error:

Similarly, assigning to a constant literal like a string also causes an error:

2. Assigning Inside a Condition Statement

Condition statements like if and while expect a boolean expression, not an assignment.

Accidentally using = instead of == leads to an assignment inside the condition, causing invalid code:

The condition x = 5 assigns 5 to x, when we meant to check if x == 5.

3. Confusing Precedence of Operators

The assignment operator = has lower precedence than other operators like + , * . So code like this:

Is treated as

This essentially tries to assign 10 to the temporary rvalue x + 5 , causing an error.

4. Assigning to the Wrong Operand in Declarations

When declaring multiple variables in one statement, we must take care to assign to the correct identifier on the left side:

This assigns 10 to y instead of x due to ordering.

5. Overloaded Assignment Operator Issues

Assignment operators can be overloaded in classes. If the overloaded assignment operator is not implemented correctly, it can lead to this error.

For example, overloaded assignment should return a modifiable lvalue but sometimes programmers mistakenly return a temporary rvalue instead.

6. Assigning to Temporary Rvalues

Temporary rvalues that get created in expressions cannot be assigned to:

Some other examples are trying to assign to literals directly or dereferencing an incorrect pointer location.

7. Assigning to Array Elements Incorrectly

Only modifiable lvalues pointing to valid memory can be assigned to.

Trying to assign to an out of bounds array index is invalid:

Diagnosing the Error in Your Code

Now that we‘ve seen common causes of the error, let‘s look at how to diagnose it when it shows up in our code:

  • Examine the full error message – it will indicate the exact expression that is invalid.
  • Ensure the expression can be assigned to based on its type – is it a modifiable lvalue?
  • Double check precedences of operators on the line causing issues. Add parentheses if needed to force intended precedence.
  • If assigning to a user-defined type, check if overloaded assignment operator is correct.
  • For conditionals and loops, verify == and = are not mixed up.
  • Make sure all variables being assigned to are valid, declared identifiers.
  • If assigning to an array element, index boundaries must be correct.
  • Look nearby for typos like swapping . and -> when accessing members.
  • Enable all compiler warnings and pedantic errors to catch related issues.

With some careful analysis of the code and error messages, identifying the root cause becomes much easier.

Resolving the Error Through Correct Modifiable Lvalues

Once we diagnose the issue, it can be resolved by using a valid modifiable lvalue on the left hand side of the assignment:

  • Declare normal variables without const that can be assigned to
  • Use dereferenced pointers like *ptr = 5 instead of direct literals
  • Call functions that return non-const lvalue references like int& func()
  • Use array element indices that are in bounds
  • Access member fields of objects correctly like obj.member not obj->member
  • Store rvalues in temporary variables first before assigning
  • Ensure operator precedence resolves properly by adding parentheses
  • Return proper lvalue references from overloaded assignment operators

Let‘s see a couple of examples fixing code with this error:

1. Fixing Const Assignment

2. Fixing Conditional Assignment

3. Fixing Invalid Array Index

By properly understanding lvalues vs rvalues in C++, we can find and fix the root causes of this error.

Best Practices to Avoid "Expression Must Be a Modifiable Lvalue" Errors

Learning from the examples and causes above, we can establish coding best practices that help avoid these kinds of errors:

  • Clearly understand difference between lvalues and rvalues before writing complex code.
  • Enable all compiler warnings to catch errors early. Pay attention to warnings!
  • Be very careful when overloading assignment operators in classes.
  • Do not combine multiple assignments in one statement. Break them up over separate lines.
  • Use const judiciously on values that do not need modification.
  • Use static_assert to validate assumptions about types and constants.
  • Use == for comparisons, = only for assignment. Avoid mixing them up.
  • Be careful with operator precedence – add parentheses when unsure.
  • Initialize variables properly when declared and avoid unintended fallthrough assignments.
  • Use descriptive variable names and formatting for readability.
  • Validate indices before accessing elements of arrays and vectors.
  • Handle returned temporaries from functions carefully before assigning.
  • Run regular static analysis on code to detect issues early.

Adopting these best practices proactively will help us write code that avoids lvalue errors.

Summary and Key Lessons

The cryptic "expression must be a modifiable lvalue" error in C++ is trying to tell us that we improperly tried assigning to something that cannot be assigned to in the language.

By learning lvalue/rvalue concepts deeply and following best practices around assignments, we can eliminate these kinds of bugs in our code.

Some key lessons:

  • Lvalues represent identifiable memory locations that can be modified. Rvalues do not.
  • Use non-const variables and valid references/pointers as left operands in assignments.
  • Be extremely careful inside conditionals, loops and declarations.
  • Understand and properly handle operator precedence and overloadable operators.
  • Enable all compiler warnings to catch issues early.
  • Adopt defensive programming practices with constants, arrays, temporaries etc.

Persistently applying these lessons will ensure we write assignment-bug-free C++ code!

You maybe like,

Related posts, a complete guide to initializing arrays in c++.

As an experienced C++ developer, few things make me more uneasy than uninitialized arrays. You might have heard the saying "garbage in, garbage out" –…

A Comprehensive Guide to Arrays in C++

Arrays allow you to store and access ordered collections of data. They are one of the most fundamental data structures used in C++ programs for…

A Comprehensive Guide to C++ Programming with Examples

Welcome friend! This guide aims to be your one-stop resource to learn C++ programming concepts through examples. Mastering C++ is invaluable whether you are looking…

A Comprehensive Guide to Initializing Structs in C++

Structs in C++ are an essential composite data structure that every C++ developer should know how to initialize properly. This in-depth guide will cover all…

A Comprehensive Guide to Mastering Dynamic Arrays in C++

As a C++ developer, few skills are as important as truly understanding how to work with dynamic arrays. They allow you to create adaptable data…

A Comprehensive Guide to Pausing C++ Programs with system("pause") and Alternatives

As a C++ developer, having control over your program‘s flow is critical. There are times when you want execution to pause – whether to inspect…

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

lvalues references and rvalues references in C++ with Examples

Prerequisites: lvalue and rvalue in C++ , References in C++ “l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the ‘&’ before the name of the variable.

Example:  

Below is the implementation for lvalue and rvalue:

Explanation : The following code will print True as both the variable are pointing to the same memory location. b is just an alternative name to the memory assigned to the variable a. The reference declared in the above code is lvalue reference (i.e., referring to variable in the lvalue) similarly the references for the values can also be declared.

rvalue references have two properties that are useful :  

  • rvalue references extend the lifespan of the temporary object to which they are assigned.
  • Non-const rvalue references allow you to modify the rvalue.

Important: lvalue references can be assigned with the rvalues but rvalue references cannot be assigned to the lvalue . 

Uses of the lvalue references :  

  • lvalue references can be used to alias an existing object.
  • They can also be used to implement pass-by-reference semantics.

Note: When the function return lvalue reference the expression becomes lvalue expression.

Uses of rvalue references :  

  • They are used in working with the move constructor and move assignment.
  • cannot bind non-const lvalue reference of type ‘ int& ‘ to an rvalue of type ‘int’.
  • cannot bind rvalue references of type ‘ int&& ‘ to lvalue of type ‘int’.

Program 1:   

Program 2:  

author

Please Login to comment...

Similar reads.

  • C++-References
  • cpp-references

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Network Sites:
  • Technical Articles
  • Market Insights

All About Circuits

  • Or sign in with

All About Circuits

C++ error: "Non-lvalue error in assignment"

Join our engineering community sign-in with:.

  • Embedded & Programming
  • Programming & Languages
  • Thread starter EEMajor
  • Start date Sep 12, 2006
  • Search Forums

Greetings everyone, I am thankful for any help that you may give me. I am working on a program that takes a trips start time and end time, then shaves 25% off the time it takes to complete the trip. However, while doing a static cast, I get the error of 'non-lvalue in assignment'. Everything else seems to work, at least from what I can tell. There are no other errors or warnings during an attempt to compile. Here is my source code: ------------------------------------------------------------------------------------------------------------------------------------ #include <iostream> #include <iomanip> using namespace std; int main () { int starttime = 0; cout << "\nPlease enter the start time for the old trip in 24 hour format (hhmm): "; cin >> starttime; cin.get(); int endtime = 0; cout << "\nPlease enter the end time for the old trip in 24 hour format (hhmm) :"; cin >> endtime; cin.get(); // Declare integers c and pt for static casting later. int newtime = 0; int pt = 0; //Get hours and minutes from the start time float hours = endtime / 100 - starttime / 100; float mins = endtime % 100 - starttime % 100; float starthours = starttime/100; float startmins = starttime%100; // Take Minutes, divide by sixty to get hours(from minutes) float minToHours = mins/60.0; // Same as above, but with the starting minutes float startMin = startmins/60.0; // Get the total hours (from minutes to hours, and regular hours) float added = minToHours + hours; // Same as above, but with starting minutes and hours float added1 = startMin + starthours; float newhours = added - (added / 4); float pretime = added1 + newhours; static_cast<int>(pt) = added1 + newhours; float fmins = pretime - pt; // Declare final numbers for the newtime calculation float newHours = pt * 100; float newMinutes = fmins * 60; static_cast<int>(newtime) = newHours + newMinutes; cout.fill ('0'); cout << "Your new ending time is: " << setw(4) << newtime << endl; system("PAUSE"); return 0; } ------------------------------------------------------------------------------------------------------------------------------------------------- These are the two static casts I am having problems with: static_cast<int>(pt) = added1 + newhours; static_cast<int>(newtime) = newHours + newMinutes; Again, thank you for the help!  

Okay, I figured it out on my own after a good nights sleep and a little more research. I am posting the solution simply for anyone who may in the future be searching for similar information. In my original source code I did this: static_cast<int>(pt) = added1 + newhours; My problem is that the static_cast operator uses the parenthetical statement, and doesn't really listen to anything after that. So, the correct way to static cast the about red line is this way: static_cast<int>(pt = added1 + newhours); So, all in all a simple mistake. Gotta love that about programming, BE VERY carefull about what you type! It makes a difference! DISCLAIMER: I am no programming expert by any stretch of the imagination. This information worked for me, with the MinGW Developer Studio. It may not work with a different compiler, or you may not even have the problem I did. I dunno!  

As far as I know, static_cast take a value of any type and typecast it to a given type. It's similar to regular C typecast operator, but stricter. The way to use the static_cast is as follows: cast_value = static_cast<type>(value); For example: double d = 15.4; int i = static_cast<int>(d); In your original code, instead of typecasting the value, you typecast the left hand value contained in the variable, which of course would do nothing value-wise because it is already an integer. It also throws the compiler off, because instead of treating the left hand statement as a variable in where the right hand value would be assigned, the static_cast actually convert the _value_ of the variable to an int and we all know that we can't assign the right hand value into another value. This is why the compiler came up with the non l-value error in assignment. Your subsequent typecasting also not entirely accurate, instead of typecasting the r-value, you actually typecast the _entire_ statement, and do nothing with the typecasting result. However, the value contained in variable pt is correct, because the assignment actually cast the value automatically (when you assigned a float to an int variable). Depending on the compiler and warning/error settings, this should, however, throws a warning on assignment of incorrect type. See the example above for correct usage.  

n9352527, Thank you very much for the information! I appreciate the response. That does make more sense, good to learn. Thanks again.  

excuse me but i received the same thing (Non-lvalue in assignment) when i was doing my homework. here is the code : #include <iostream> #include <cstdlib> #include <cstdio> using namespace std; int main () { double a = 0.0; double b = 0.0; double c = 0.0; double d1; double d2; double d3; double x = 0; cout << "Please input the 3 remainders.\n"; cin >> a; cin >> b; cin >> c; 3*x + a = d1; 5*x+b=d2; 7*x+c=d3; while ( d1 != d2 != d3) { x++; } cout << ("Your number is", d1 ,"."); system ("PAUSE"); return 0; } Please help!!!!  

Mark44

EEMajor said: These are the two static casts I am having problems with: static_cast<int>(pt) = added1 + newhours; static_cast<int>(newtime) = newHours + newMinutes; Click to expand...
alphaboy95 said: excuse me but i received the same thing (Non-lvalue in assignment) when i was doing my homework. here is the code : #include <iostream> #include <cstdlib> #include <cstdio> using namespace std; int main () { double a = 0.0; double b = 0.0; double c = 0.0; double d1; double d2; double d3; double x = 0; cout << "Please input the 3 remainders.\n"; cin >> a; cin >> b; cin >> c; 3*x + a = d1; // <=== error here 5*x+b=d2; // <=== error here 7*x+c=d3; // <=== error here while ( d1 != d2 != d3) // <=== possible error here { x++; } cout << ("Your number is", d1 ,"."); // I doubt that this will work system ("PAUSE"); // I'm not sure, but I don't think this will work return 0; } Please help!!!! Click to expand...
Thread starter Similar threads Forum Replies Date
0
0
13
16
9
Similar threads

You May Also Like

error non lvalue in assignment

Makers and Learners Rejoice! Arduino Debuts Plug and Make Kit

by David Peterson, Control.com

error non lvalue in assignment

My Favorites From Sensors Converge 2024

by Dale Wilson

error non lvalue in assignment

Certifications and Collabs: Chipmakers Advance the Automotive Market

by Jake Hertz

error non lvalue in assignment

MIT’s Implantable Microphone May Lead to Internal Cochlear Implants

by Duane Benson

All About Circuits Logo

non-lvalue in assignment

Member Avatar for beatenbob

Hi all, I know this is a trivial question but I really got stuck. I keep getting "non-1value in assignment" when trying to access the pointer variable "next" using the getNext() function. It didn't show any error if I change the last 2 lines to

The problem arises when I try using getNext(), as shown in the code below(located in the last 2 lines). This is my school assignments and I'm not allowed to set the pointer "next" to public.. kindly need your help as I've already stuck in this for so long.

  • 2 Contributors
  • 6 Hours Discussion Span
  • Latest Post 13 Years Ago Latest Post by jonsca

Pass your after pointer to your temp_ptr's setNext method, something like temp_ptr->setNext(after->getNext());

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Insert Code Block

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Compiler Error "non-lvalue in assignment

  Compiler Error "non-lvalue in assignment"

error non lvalue in assignment

missang() { (A == 0 && B != 0 && C != 0) { A = 180 - C - B; } (A != 0 && B == 0 && C !=0) { B = 180 - A - C; } (A != 0 && B != 0 && C == 0) { C = 180 - A - B; } }
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

c++: non-Ivalue in assignment

Hi i would like to make an external single linked list. I have a problem with "Non-Ivalue in assignment" and its occuring on line "this = currP->next" i tried making it currP.next but its also producing an error

Luchian Grigore's user avatar

  • 3 this is not a variable. It is a keyword representing the current object. You can not change the current object by trying to set it. –  Loki Astari Commented Nov 7, 2011 at 9:37

2 Answers 2

An lvalue is a variable that can reside at the left side of the equal operator. This means its value can be changed. You can't change the value of this , it's just not permitted, therefore the error.

You could re-write your function as follows:

deleteNode() will now return a pointer to the start of the rest of the list and the recursive algorithm will concatenate the first part with the last part. It's not tested so a few adjustments may be necessary but I hope you get the point.

  • 1 To elaborate a little on this answer, instead of assigning to this , you could copy the data which for a simple class like this you can do with *this = *currP->next . If you don't know what the difference is, read more about pointer dereferencing . –  Some programmer dude Commented Nov 7, 2011 at 9:42
  • You might get a more detailed answer on codereview , but in general, I'd question why removing an item from a list was a method of a node at all. –  Useless Commented Nov 7, 2011 at 9:43
  • im trying to make node and list as one struct instead of list and node separated XD.. –  jko Commented Nov 7, 2011 at 9:48
  • @Useless Removing the node might make sense (in which case, the best name for the function isn't deleteNode , but ~Node ---the destructor), but his function apparently deletes an arbitrary node further down in the list. Such a function should be a member of the list class itself, and not of the node. –  James Kanze Commented Nov 7, 2011 at 9:48
  • 2 @jko - I see that, but I'm suggesting it's a poor seperation of concerns, as @JamesKanze also points out. It could be reasonable to have a list class with just one member: node head; and move the list-management operations into there. Also: consider how you represent an empty list: is it going to be a NULL node pointer, or a magic sentinel node? ... Anyway, this is rapidly getting too big for a comment. –  Useless Commented Nov 7, 2011 at 9:55

A lvalue is a semantic rule. It means "left-value".

Examples of lvalues are:

  • A variable. ie "a"
  • A memory address. ie "a[4]" or "*(a+8)"

this is not a lvalue. You just can't assign anything to it. It's the reference to the method caller.

Victor's user avatar

  • how could i make the method caller variable "next" point to where "currP->next" points? –  jko Commented Nov 7, 2011 at 9:42
  • this->next = currP->next; You can access this like a normal variable, you just can't assign anything to it. –  Victor Commented Nov 7, 2011 at 9:48

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ pointers or ask your own question .

  • The Overflow Blog
  • This developer tool is 40 years old: can it be improved?
  • Unpacking the 2024 Developer Survey results
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Introducing an accessibility dashboard and some upcoming changes to display...
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Feynman famously criticized the Space Shuttle program for not delivering any value to science. Did things improve in that regard since the 1980s?
  • How do I tell whether a Ginkgo biloba seedling is male or female?
  • Does the sum of the reciprocal highly composite numbers converge or diverge?
  • If an agreement puts some condition on a file, does the condition also apply to its content? (the content itself is under CC BY-SA)
  • “Ryan was like, ‘Listen, if we need cue cards…’ and I was like, ‘Cue cards? I’m showing up off-book,'” Evans recounted
  • What does the circuit shown in the picture do?
  • Is there a formal definition of an animal?
  • Old story about the shape of a robot and its ability to not break down
  • How to avoid crashing while mountain biking
  • How is clang able to evaluate loops without getting stuck in an infinite loop?
  • Trouble understanding how these stock prices are being reported
  • Is this really a neon lamp?
  • What is the most economical way to fly small planes?
  • Who checks and balances SCOTUS?
  • Do something you can't do in Brainfuck
  • How could ocean liners survive in a major capacity after large jet airliners become common?
  • How to measure out fresh herbs when the recipe calls for 'a tablespoon of chopped herb'?
  • Is brush-on primer on steel panels supposed to be soft?
  • Running the plot of Final Fantasy X
  • Why do many CVT cars appear to index gears during normal automatic operation?
  • Word/phrase for avoiding a task because it has a lot of unknowns
  • Schengen visa expires during my flight layover
  • Reference for the proof that Möbius transformations extend to isometries of hyperbolic 3-space
  • What role can scrum master have/take when product owners differ from opinion?

error non lvalue in assignment

Home Posts Topics Members FAQ

New Member |Select|Wrap|Line Numbers |Select|Wrap|Line Numbers 10529 New Member
Message
 

Sign in to post your reply or Sign up for a free account.

Similar topics

| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use .

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.

IMAGES

  1. Technical Notes: Initialization of lvalue-reference with non-lvalue

    error non lvalue in assignment

  2. c语言 提示:lvalue required as left operand of assignment

    error non lvalue in assignment

  3. From lvalue, prvalue, and xvalue to move semantics in C++

    error non lvalue in assignment

  4. [Solved] Error: cannot bind non-const lvalue reference of

    error non lvalue in assignment

  5. [Solved] lvalue required as left operand of assignment

    error non lvalue in assignment

  6. c语言报错 error: lvalue required as left operand of assignment是咋回事呀-CSDN博客

    error non lvalue in assignment

VIDEO

  1. పిఠాపురం MLA తాలూకా నెంబర్ ప్లేట్ పై స్పందించిన పవన్ l Pitapuram MLA Pawan Kalyan lValue Updates TV

  2. Fix syntax error: non-declaration statement outside function body in Golang

  3. L value and R value

  4. How to fix non-descriptive link text in Webflow in under 2 minutes

  5. C Language prefix and postfix decrement operation in larger expression in Hindi

  6. C++ Variables, Literals, an Assignment Statements [2]

COMMENTS

  1. Why can't *pointer+offset be used as an l-value? ("error: non-lvalue in

    Errors with c++ pointers to arrays: invalid type argument of unary * (have 'int), lvalue required as left operand of assignment 3 lvalue required as left operand of assignment c++ arrays

  2. error non-lvalue in assignment

    Since this is an assignment I would appreciate not getting code for an answer, but rather if someone can tell me where to look for the issue? Here is the set function I am trying to write. The private data in this class is an array, Hand TheHand[3] and int numCards(the number of cards in TheHand) in the .h

  3. non-lvalue in assignment?? WTF?

    An L-Value (Left-Value) is an operand* that can appear on both the left-hand & right-hand side of an assignment. L-Values generally have an address in memory, so the compiler knows where to store the value on the right-hand side. An R-Value is also an operand that generally doesn't have an address in memory. These are usually magic constants or ...

  4. non-lvalue in assignment

    Zhuge (4664) The assignment (=) operator makes the left side equal to the right. The right side is the constant 1, which can't be changed to be equal to whatever is at ary [j]. In other words, the constant 1 is not a proper l-value for the operator. You should just switch the order of the operands.

  5. Demystifying C++'s "lvalue Required as Left Operand of Assignment" Error

    The key phrase is "lvalue required as left operand of assignment." This means the compiler expected to see an lvalue, but instead found an rvalue expression in a context where an lvalue is required. Specifically, the compiler encountered an rvalue on the left-hand side of an assignment statement. Only lvalues are permitted in that position ...

  6. Understanding lvalues and rvalues in C and C++

    A simple definition. This section presents an intentionally simplified definition of lvalues and rvalues.The rest of the article will elaborate on this definition. An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address).. rvalues are defined by exclusion, by saying that every expression is either an lvalue or an rvalue.

  7. 12.3

    An lvalue reference (commonly just called a reference since prior to C++11 there was only one type of reference) acts as an alias for an existing lvalue (such as a variable).. To declare an lvalue reference type, we use an ampersand (&) in the type declaration: int // a normal int type int& // an lvalue reference to an int object double& // an lvalue reference to a double object

  8. Demystifying the "Expression Must Be a Modifiable Lvalue" Error in C++

    Call functions that return non-const lvalue references like int& func() Use array element indices that are in bounds ... Let's see a couple of examples fixing code with this error: 1. Fixing Const Assignment // Broken const float PI = 3.14; PI = 2.5; // Fixed float PI = 3.14; PI = 2.5; 2. Fixing Conditional Assignment

  9. lvalues references and rvalues references in C++ with Examples

    Note: When the function return lvalue reference the expression becomes lvalue expression. Uses of rvalue references: They are used in working with the move constructor and move assignment. cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'.

  10. C++ error: "Non-lvalue error in assignment"

    The errors you mention about non lvalues come from the first three lines I marked as errors. An assignment statement has to have a variable (an lvalue) on the left side, and some value on the right side. The l in lvalue stands for left. You need to rewrite these three lines following this model: Rich (BB code):

  11. Non-Lvalue in assignment error

    You can assign something to a variable, but not to "meter2 - meter". You probably meant meter2 = remainder + meter;

  12. error: non-lvalue in assignment

    home > topics > c / c++ > questions > error: non-lvalue in assignment Join Bytes to post your question to a community of 473,363 software developers and data experts. error: non-lvalue in assignment

  13. c++

    Hi all, I know this is a trivial question but I really got stuck. I keep getting "non-1value in assignment" when trying to access the ...

  14. c

    r=(5&&c)=10; which is equivalent to either. r= 0 =10; or. r= 1 =10; The reason behind either expression is that 5 && c will return either true or false depending upon the value of c (whether it is 0 or not). As per the comment by OP. How to wire r=5 and c=10. You can do this as.

  15. Compiler Error "non-lvalue in assignment

    when i compile this code i get "error: non-lvalue in assignment" why? Just so you know, this program soves for the missing parts of a triangle, los and loc are law of sines and law of cosines respectively. The errors are commented and are in the last appx 30 lines of code. /* Note, a capital letter represents an angle measure and

  16. error: non-lvalue in assignment

    error: non-lvalue in assignment. C / C++ Forums on Bytes. >>Thanks for the response.... Point Taken but this is not the case. Thus, if a person writes a text file on her or his computer and does not use UNICODE to save it, the current code page is used.

  17. c

    The name lvalue comes originally from the assignment expression E1 = E2, in which the left operand E1 is required to be a (modifiable) lvalue. It is perhaps better considered as representing an object "locator value". What is sometimes called rvalue is in this International Standard described as the "value of an expression".

  18. pointers

    1. To elaborate a little on this answer, instead of assigning to this, you could copy the data which for a simple class like this you can do with *this = *currP->next. If you don't know what the difference is, read more about pointer dereferencing. - Some programmer dude.

  19. error: non-lvalue in assignment

    Thus, if a person writes a text file on her or his computer and does not use UNICODE to save it, the current code page is used. If this file is given to someone with some other current codepage, the file is not displayed correctly. Simply converting the file to Unicode will make the data display properly. When performing the encoding process ...