• C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

lvalue and rvalue in C language

Lvalue:- .

lvalue simply means an object that has an identifiable location in memory (i.e. having an address).

  • In any assignment statement “lvalue” must have the capability to store the data.
  • lvalue cannot be a function, expression (like a+b) or a constant (like 3 , 4 , etc.).

L-value : “l-value” refers to memory location which identifies an object. l-value may appear as either left hand or right hand side of an assignment operator(=). l-value often represents as identifier. Expressions referring to modifiable locations are called “ modifiable l-values “. A modifiable l-value cannot have an array type, an incomplete type, or a type with the const attribute. For structures and unions to be modifiable lvalues , they must not have any members with the const attribute. The name of the identifier denotes a storage location, while the value of the variable is the value stored at that location. An identifier is a modifiable lvalue if it refers to a memory location and if its type is arithmetic, structure, union or pointer. For example, if ptr is a pointer to a storage region, then *ptr is a modifiable l-value that designates the storage region to which ptr points. In C, the concept was renamed as “locator value” , and referred to expressions that locate (designate) objects. The l-value is one of the following:

  • The name of the variable of any type i.e. , an identifier of integral, floating, pointer, structure, or union type.
  • A subscript ([ ]) expression that does not evaluate to an array.
  • A unary-indirection (*) expression that does not refer to an array
  • An l-value expression in parentheses.
  • A const object (a nonmodifiable l-value).
  • The result of indirection through a pointer, provided that it isn’t a function pointer.
  • The result of member access through pointer(-> or .)

p = &a; // ok, assignment of address // at l-value

&a = p; // error: &a is an r-value

( x < y ? y : x) = 0; // It’s valid because the ternary // expression preserves the "lvalue-ness" // of both its possible return values

r-value simply means, an object that has no identifiable location in memory (i.e. having an address).

  • Anything that is capable of returning a constant expression or value.
  • Expression like a+b will return some constant.

R-value : r-value” refers to data value that is stored at some address in memory. A r-value is an expression, that can’t have a value assigned to it, which means r-value can appear on right but not on left hand side of an assignment operator(=). 

Note : The unary & (address-of) operator requires an l-value as its operand. That is, &n is a valid expression only if n is an l-value. Thus, an expression such as &12 is an error. Again, 12 does not refer to an object, so it’s not addressable. For instance, 

Remembering the mnemonic, that l-values can appear on the left of an assignment operator while r-values can appear on the right.

Reference: https://msdn.microsoft.com/en-us/library/bkbs2cds.aspx

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

logo

Solve error: lvalue required as left operand of assignment

In this tutorial you will know about one of the most occurred error in C and C++ programming, i.e.  lvalue required as left operand of assignment.

lvalue means left side value. Particularly it is left side value of an assignment operator.

rvalue means right side value. Particularly it is right side value or expression of an assignment operator.

In above example  a  is lvalue and b + 5  is rvalue.

In C language lvalue appears mainly at four cases as mentioned below:

  • Left of assignment operator.
  • Left of member access (dot) operator (for structure and unions).
  • Right of address-of operator (except for register and bit field lvalue).
  • As operand to pre/post increment or decrement for integer lvalues including Boolean and enums.

Now let see some cases where this error occur with code.

When you will try to run above code, you will get following error.

Solution: In if condition change assignment operator to comparison operator, as shown below.

Above code will show the error: lvalue required as left operand of assignment operator.

Here problem occurred due to wrong handling of short hand operator (*=) in findFact() function.

Solution : Just by changing the line ans*i=ans to ans*=i we can avoid that error. Here short hand operator expands like this,  ans=ans*i. Here left side some variable is there to store result. But in our program ans*i is at left hand side. It’s an expression which produces some result. While using assignment operator we can’t use an expression as lvalue.

The correct code is shown below.

Above code will show the same lvalue required error.

Reason and Solution: Ternary operator produces some result, it never assign values inside operation. It is same as a function which has return type. So there should be something to be assigned but unlike inside operator.

The correct code is given below.

Some Precautions To Avoid This Error

There are no particular precautions for this. Just look into your code where problem occurred, like some above cases and modify the code according to that.

Mostly 90% of this error occurs when we do mistake in comparison and assignment operations. When using pointers also we should careful about this error. And there are some rare reasons like short hand operators and ternary operators like above mentioned. We can easily rectify this error by finding the line number in compiler, where it shows error: lvalue required as left operand of assignment.

Programming Assignment Help on Assigncode.com, that provides homework ecxellence in every technical assignment.

Comment below if you have any queries related to above tutorial.

Related Posts

Basic structure of c program, introduction to c programming language, variables, constants and keywords in c, first c program – print hello world message, 6 thoughts on “solve error: lvalue required as left operand of assignment”.

' src=

hi sir , i am andalib can you plz send compiler of c++.

' src=

i want the solution by char data type for this error

' src=

#include #include #include using namespace std; #define pi 3.14 int main() { float a; float r=4.5,h=1.5; {

a=2*pi*r*h=1.5 + 2*pi*pow(r,2); } cout<<" area="<<a<<endl; return 0; } what's the problem over here

' src=

#include using namespace std; #define pi 3.14 int main() { float a,p; float r=4.5,h=1.5; p=2*pi*r*h; a=1.5 + 2*pi*pow(r,2);

cout<<" area="<<a<<endl; cout<<" perimeter="<<p<<endl; return 0; }

You can't assign two values at a single place. Instead solve them differetly

' src=

Hi. I am trying to get a double as a string as efficiently as possible. I get that error for the final line on this code. double x = 145.6; int size = sizeof(x); char str[size]; &str = &x; Is there a possible way of getting the string pointing at the same part of the RAM as the double?

' src=

Leave a Comment Cancel Reply

Your email address will not be published. Required fields are marked *

Next: Modifying Assignment , Previous: Simple Assignment , Up: Assignment Expressions   [ Contents ][ Index ]

7.2 Lvalues

An expression that identifies a memory space that holds a value is called an lvalue , because it is a location that can hold a value.

The standard kinds of lvalues are:

  • A variable.
  • A pointer-dereference expression (see Pointer Dereference ) using unary ‘ * ’.
  • A structure field reference (see Structures ) using ‘ . ’, if the structure value is an lvalue.
  • A structure field reference using ‘ -> ’. This is always an lvalue since ‘ -> ’ implies pointer dereference.
  • A union alternative reference (see Unions ), on the same conditions as for structure fields.
  • An array-element reference using ‘ [ … ] ’, if the array is an lvalue.

If an expression’s outermost operation is any other operator, that expression is not an lvalue. Thus, the variable x is an lvalue, but x + 0 is not, even though these two expressions compute the same value (assuming x is a number).

An array can be an lvalue (the rules above determine whether it is one), but using the array in an expression converts it automatically to a pointer to the zeroth element. The result of this conversion is not an lvalue. Thus, if the variable a is an array, you can’t use a by itself as the left operand of an assignment. But you can assign to an element of a , such as a[0] . That is an lvalue since a is an lvalue.

invalid lvalue in assignment c

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.

invalid lvalue in assignment c

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 .

C Board

  • Today's Posts
  • C and C++ FAQ
  • Mark Forums Read
  • View Forum Leaders
  • What's New?
  • Get Started with C or C++
  • C++ Tutorial
  • Get the C++ Book
  • All Tutorials
  • Advanced Search

Home

  • General Programming Boards
  • C Programming

:523: error: invalid lvalue in assignment

  • Getting started with C or C++ | C Tutorial | C++ Tutorial | C and C++ FAQ | Get a compiler | Fixes for common problems

Thread: :523: error: invalid lvalue in assignment

Thread tools.

  • Show Printable Version
  • Email this Page…
  • Subscribe to this Thread…

Search Thread

  •   Advanced Search
  • Linear Mode
  • Switch to Hybrid Mode
  • Switch to Threaded Mode
  • View Profile
  • View Forum Posts

nasim751 is offline

hello, how can i solve this problem ........ error: invalid lvalue in assignment Code: if(c==0) { (char **)sTmp= &sd->source; nl=sd->sbound; } this is my structure Code: struct _sd { char source[MAXHOSTIP][MAXHOSTLENGHT]; char dest[MAXHOSTIP][MAXHOSTLENGHT]; int sbound; int dbound; }; struct _tcp_udp { struct _sd sd; int ports[MAXPORTS]; }; struct _tcprst { struct _sd sd; int seq; int source_port; int dest_port; }; struct _icmp_igmp { struct _sd sd; }; struct listofip { struct _tcp_udp tcp; struct _tcp_udp udp; struct _icmp_igmp icmp; struct _icmp_igmp igmp; struct _tcprst trst; }ltp; but when i am using like this Code: if(c==0) { sTmp= &sd->source; nl=sd->sbound; } Code: int ResolveHostIP(char* argv, struct _sd *sd) { int i,c=0,nC,nl; struct hostent*hp; struct _sTmp { char szTmp[MAXHOSTIP][MAXHOSTLENGHT]; }*sTmp; Getting this warning warning: assignment from incompatible pointer type what will be the right syntax.

tabstop is offline

So if that last bit of code is to be believed sTmp points to a struct _sTmp? If so, the obvious (and, fortunately, correct) way to do this would be to memcpy sd->source to sTmp->szTmp. They're both two-dimensional arrays of chars, which means that the memory is already there (arrays allocate their own memory) and guaranteed to be both (a) in one continuous piece and (b) of the same size (assuming of course that sTmp and sd both point to legitimate structures and not to Hoboken).

Elysia is offline

Btw, as for your errors... It's illegal to do a cast on the left side of the type you're assigning to. You must cast the source (what you're assigning) to the correct destination type (what you're assigning to). Note that in this case, as tabstop so kindly points out, it may not be the right thing to do. Example: Code: int myint = 0; float myfloat = 0.0f; int* pMyInt = NULL; pMyInt = (int*)&myfloat; /* Not (float*)pMyInt = &myfloat; */ By an explicit cast, it works. But this example is not recommended practice. And the warning means that you're trying to assign a pointer of type Y* to type X*, or in other words, you're trying to assign a pointer pointing to a different type than the pointer you're trying to assign to. Example: Code: int myint = 0; float myfloat = 0.0f; int* pMyInt = NULL; pMyInt = &myfloat; This, for some reason, compiles in C, but is bad, because &myfloat is float* and pMyInt is int*, thus different types, hence the warning.
Originally Posted by Adak io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions. Originally Posted by Salem You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much. Outside of your DOS world, your header file is meaningless.

matsp is offline

You CAN use casts on the left-side, but not direct type conversions, e.g: Code: int *pInt; float f = 3.13; *(float **)&pInt = &f; -- Mats
Compilers can produce warnings - make the compiler programmers happy: Use them! Please don't PM me for help - and no, I don't do help over instant messengers.
The standard is just full of loopholes and exceptions everywhere, isn't it?
Originally Posted by Elysia The standard is just full of loopholes and exceptions everywhere, isn't it? Well, it's really about the rule of what a lvalue is: It is something that can be assigned to, and (float)blah is not a valid lvalue, but *(float *) is, for example [then, to make valid code, executable code, you have to make sure that casted value points to a valid memory location of the correct size for a float - but this construct is OFTEN used for addressing directly to hardware memory locations - rarely with float, but with specificly sized integers]. -- Mats
Unfortunately, the whole l-value vs r-value and rules and regulations are becoming so extremely complicated with all exceptions and rules it's impossible to tell what's possible and not. If a cast can be done before the l-value and it produces a correct l-value, then it should be possible. This also means a cast to a non-pointer type. Technically, it might create a new, temporary variable as a result of the operation, but then again, it might not - it could be implemented either way.
Originally Posted by Elysia Unfortunately, the whole l-value vs r-value and rules and regulations are becoming so extremely complicated with all exceptions and rules it's impossible to tell what's possible and not. If a cast can be done before the l-value and it produces a correct l-value, then it should be possible. This also means a cast to a non-pointer type. Technically, it might create a new, temporary variable as a result of the operation, but then again, it might not - it could be implemented either way. The rule is actually simple: an lvalue is anything that can be assigned to. A type-case of something can not be assigned to, a dereference of something that is a typecast of a pointer can. -- Mats
That makes no sense. A cast changes the type of something to another, so changing from int to float should still be valid, without the use of pointers and dereferencing them.
Originally Posted by Elysia That makes no sense. A cast changes the type of something to another, so changing from int to float should still be valid, without the use of pointers and dereferencing them. Yes, but remember: you're assigning to things. If you have char b and you try to assign something to (float) b, where are you going to put it? There's no memory address there. But assigning to a dereferenced pointer always has a memory address available (to wit, the pointer).
That's what I figured and which is also what I asked why the implementation cannot simply change the type of the variable assigned to first and then assign. Perhaps it wouldn't work if the type is too large, though. But in any case, as with any temporaries, the compiler could create a temporary to assign to, then assign to the destination. But I'm guessing this is not allowed in the standard.
  • Private Messages
  • Subscriptions
  • Who's Online
  • Search Forums
  • Forums Home
  • C++ Programming
  • C# Programming
  • Game Programming
  • Networking/Device Communication
  • Programming Book and Product Reviews
  • Windows Programming
  • Linux Programming
  • General AI Programming
  • Article Discussions
  • General Discussions
  • A Brief History of Cprogramming.com
  • Contests Board
  • Projects and Job Recruitment

subscribe to a feed

  • How to create a shared library on Linux with GCC - December 30, 2011
  • Enum classes and nullptr in C++11 - November 27, 2011
  • Learn about The Hash Table - November 20, 2011
  • Rvalue References and Move Semantics in C++11 - November 13, 2011
  • C and C++ for Java Programmers - November 5, 2011
  • A Gentle Introduction to C++ IO Streams - October 10, 2011

Similar Threads

Invalid lvalue in assignment, screwy linker error - vc2005, a mini-compilier i made stuck in an infinite loop (lots of code), question on l-values..

  • C and C++ Programming at Cprogramming.com
  • Web Hosting
  • Privacy Statement
  • Open Source Software
  • Business Software
  • For Vendors
  • SourceForge Podcast
  • Site Documentation
  • Subscribe to our Newsletter
  • Support Request

Dev-C++

Please Help: 'invalid lvalue in assignment'

Open source c & c++ ide for windows.

  • Mailing Lists
  • Feature Requests
  • Create Topic
  • Stats Graph
  • dev-cpp-users 727
  • Project Developers (Delphi) 384
  • Bloodshed Software Forum 14277
  • Formatting Help

Please Help: 'invalid lvalue in assignment' document.SUBSCRIPTION_OPTIONS = { "thing": "topic", "subscribed": false, "url": "subscribe", "icon": { "css": "fa fa-envelope-o" } };

Nobody/Anonymous

Hi guys I am a univeristy student taking Music Technology, which for some reason includes a module on C Programming. I am currently working through some problems as a re-sit piece of coursework; the one I am stuck on is asking me to write a program to read in an integer and a floating point number, and send them to a function which calculates the floating point no raised to the power of the integer. I have the bare bones of the program written, but am having problems when I try to compile it. I am receiving error messages reading 'invalid lvalue in assignment', referring to the lines on which I have assigned values to storage locations. Please see below for the program of the function itself.

float raise_float (float base, int power) { int count;

I believe I also read in the guidelines to copy in my compile log? please see below for this.

C:\Documents and Settings\Chris Jordan\Desktop\C-prog Resit Coursework\6. Powers (incomplete).c: In function `raise_float': C:\Documents and Settings\Chris Jordan\Desktop\C-prog Resit Coursework\6. Powers (incomplete).c:28: error: invalid lvalue in assignment C:\Documents and Settings\Chris Jordan\Desktop\C-prog Resit Coursework\6. Powers (incomplete).c:30: error: invalid lvalue in assignment C:\Documents and Settings\Chris Jordan\Desktop\C-prog Resit Coursework\6. Powers (incomplete).c:33: error: invalid lvalue in assignment C:\Documents and Settings\Chris Jordan\Desktop\C-prog Resit Coursework\6. Powers (incomplete).c:35: error: incompatible types in return

Execution terminated

If anybody could help me at all with this; even just telling me what the error message means; it would be incredibly appreciated! many thanks, Chris

Anonymous

They are variables . Here 'i' is used as a loop counter, and 'x' is used to accumulate and ultimately return the value of the function. I imagine where he has used 'i' you intended to use 'count' which is unused in your code.

The respondent has made a (probably fair) assumption about what your code was supposed to do and completed it for you. If this was your homework assignment perhaps he should have not been quite so "helpful". He has also used a 'nasty' practice of having more that one return in a function. The correction to your code (without any such assumptions) would look like this:

float raise_float (float base, int power) { float result ;

if (power == 0) { result = 1.0f ; } else if (power == 1) { result = base ; } else { result = 999.0f; }

return result ; }

It would be better her to use a switch:

switch( power ) { case 0 : result = 1.0f ; break ;

case 1 : result = base ; break ;

default : result = 999.0f ; break ; }

The switch version is only possible because 'power' is an integer - this is not the general case in mathematics where an exponent (the correct term) is a real number (a floating point value being a machine approximation of a real number).

Note that there is a function in the standard library that performs this function far more efficiently and with real exponents using hardware FPU operations requiring no iteration (so the calculation time is constant and not a function of the exponent).

You are trying to assign a value to the raise_float function. You need to define a float variable for raise_float and use it in the calculation. Return the variable, not the function name.

lvalue is the left side value in an assignment. The statement raise_float = 1; is invalid because the variable raise_float is not defined (it is a function).

try this instead ...

float raise_float (float base, int power) {

if (power == 0) return 0;

if (power == 1) return base;

float x:=1.0; int i=0;

if (power > 1 ) * power is positive / for( i=0; i<power; ++i) x = x base; / or shorter code is x = base; */

else / power is negative / for( i=0; i<power; ++i) x = x/base; / or shorter code is x /= base; /

return x; }

rattatouie

thankyou very much both of you; its starting to fall into place now. The example above looks like it should be useful, but can't work out what the 'x' and 'i' are for, and where I need to declare them? thanks again

Log in to post a comment.

invalid lvalue in assignment c

  • Site Search Search Posts Find A Forum Thread Number Threads by Name Search FAQs
  • ENGINEERING.com
  • Eng-Tips Forums
  • Tek-Tips Forums

Tek-Tips Information Technology Professional Forums



(Programmer)

I appreciate any help

(Programmer)
If that still doesn't work, then maybe try this:
(Programmer)

So remove all those casts on the left hand side of the expression.  I've no idea what they'd achieve anyway.

What they are doing is making an r-value expression out of it, and thus causing the problem you state.

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.

(Programmer) (Programmer)
becomes
mAttr |= (1<<attr);

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.

(Programmer) (Programmer)
I don't know what changes were made to gcc 4.0, but maybe you were compiling at a lower warning level before?  I know how to change the warning level in VC++, but not in gcc.  Shouldn't be hard to find out though. (Programmer) (Programmer)

But since this is actually C++ code, that too might not work either.

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.

(Programmer)

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

and talk with other members! Already a Member?


Join Tek-Tips ® Today!

Join your peers on the Internet's largest technical computer professional community. It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More...

Register now while it's still free!

Already a member? Close this window and log in.

Join Us               Close

  • 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.

(invalid lvalue in assignment) this error happens when i run it.what does it mean?

This is the code and the compiler says there is sth wrong with line 7..

  • compiler-errors
  • ternary-operator
  • conditional-operator

Vlad from Moscow's user avatar

  • 1 It was interpreted like (m=='A' || m=='B' || m=='C' ? n=(3*a)+(5*b) : n) =(5*a)+(3*b); .Try n=(5*a)+(3*b) --> (n=(5*a)+(3*b)) or n = m=='A' || m=='B' || m=='C' ? 3*a + 5*b : 5*a + 3*b; –  BLUEPIXY Commented Oct 14, 2017 at 15:58
  • Don't hesitate to put brackets, it's not a shame, even when you're 100% sure about order of operators. –  valdo Commented Oct 14, 2017 at 18:27

2 Answers 2

Use instead

Otherwise the statement looks like

Or you could write

The conditional operator in C is defined the following way

As the assignment operator has lower priority then the compiler issues an error because the assignment is excluded from the conditional operator for the third operand

The used by you expression would be valid in C++ because in C++ the operator is defined differently

  • i tried (n=(5*a)+(3*b)) instead of n=(5*a)+(3*b) and (n=(3*a)+(5*b)) instead of n=(3*a)+(5*b) and it debugged.thanks for ur help! –  erfan Commented Oct 14, 2017 at 16:09

There is no need to use a complicated statement that confuses everyone, including the compiler. This is just as effective, and a lot easier to read:

Bo Persson's user avatar

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 compiler-errors ternary-operator conditional-operator or ask your own question .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Is there a general way to find the inverse of an automorphism of the free group?
  • Is evolution anti-entropic?
  • Fixed column width and left alignment works partially
  • Need help deciphering word written in Fraktur
  • join files/devices in linear mode together in a linux system
  • Relation between energy and time
  • Has an aircraft ever crashed due to it exceeding its ceiling altitude?
  • What does "steal so much as a single glance" mean?
  • Does quick review means likely rejection?
  • Can you find a real example of "time travel" caused by undefined behaviour?
  • Edna Andrade's Black Dragon: Winding around control points
  • How do Trinitarian Christians respond to these differences between Jesus Christ and God
  • Are hot air balloons regulated by ATC or can they fly without reporting to ATC?
  • What does ocurrido mean in this sentence?
  • Can DHCP Server detect Windows version?
  • Are there published figures on aero loss to tyre tread?
  • Schengen visa rejected 3 times
  • QGIS SQL (Virtual layer) How to change values where two geometries are equal, otherwise keep value?
  • Legality of company mandating employees to work late hours
  • GUI Interface for a command line program in C# Windows Forms
  • How artificial is the lack of 450%+/50t+ gearing on lesser 1x groups?
  • Any way to cancel C-q quoted-insert?
  • Fantasy novel with a girl, a satyr, and a gorgon escaping a circus
  • A paradox while explaining the equilibrium of books

invalid lvalue in assignment c

Home Posts Topics Members FAQ

9066 You are assigning c to the result of the conditional expression, so the
above equivalent to

((posbfr >= endbfr) ? printf("......" ) : *posbfr++) = c ;

--
Ian Collins.
<snip> Assignment is lower priority than ?:. The compiler sees your expression
as (cond ? x : y) = c;

Try explicit parentheses, like this:

(posbfr >= endbfr) ? printf("......" ) : (*posbfr++ = c) ;


Ian,
I know I am not then understanding this. I thought, given

expr1 ? expr2 : expr3;

then, if expr1 evaluates to true, then expr2 is evaluated, else if
false, expr3.

So, in the above case, is an assignment not regarded as a valid
expression?
..


Try explicit parentheses, like this:

(posbfr >= endbfr) ? printf("......" ) : (*posbfr++ = c) ; Aha...thank you.

| 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.

COMMENTS

  1. Error: invalid lvalue in assignment [in c]

    This is what complier said after I complied the program: In function 'main': Line 40: error: invalid lvalue in assignment. which is: /*Calculate area for single room*/. width * length = totalArea_single; And here's the whole code: #include <stdio.h>.

  2. pointers

    2. There are a couple of errors in the code: newPtr is declared as a pointer-to-integer, but you are casting it to pointer-to-pointer-to-integer which is wrong. list+index is also a pointer-to-integer to * (list+index) is an integer pointed to by (list+index). But you are trying to assign that to newPtr (which is also casted to wrong type as ...

  3. lvalue and rvalue in C language

    R-value: r-value" refers to data value that is stored at some address in memory. A r-value is an expression, that can't have a value assigned to it, which means r-value can appear on right but not on left hand side of an assignment operator (=). C. // declare 'a', 'b' an object of type 'int'. int a = 1, b; a + 1 = b; // Error, left ...

  4. Solve error: lvalue required as left operand of assignment

    Particularly it is left side value of an assignment operator. rvalue means right side value. Particularly it is right side value or expression of an assignment operator. Example: a = b + 5; In above example a is lvalue and b + 5 is rvalue. In C language lvalue appears mainly at four cases as mentioned below: Left of assignment operator.

  5. Assignment Expressions (GNU C Language Manual)

    7 Assignment Expressions. As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value. An assignment in C is an expression because it has a value; we call it an assignment expression.

  6. Lvalues (GNU C Language Manual)

    7.2 Lvalues. An expression that identifies a memory space that holds a value is called an lvalue, because it is a location that can hold a value.. The standard kinds of lvalues are: A variable. A pointer-dereference expression (see Pointer Dereference) using unary '*'.; A structure field reference (see Structures) using '.', if the structure value is an lvalue.

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

    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: 4 = var; // ERROR! (var + 1) ... Initially when lvalues were defined for C, it literally meant "values suitable for left-hand-side of assignment". Later, ...

  8. invalid lvalue in assignment

    When compile, the red line is error, invalid lvalue in assignment How to fix this? Code: #include <stdio.h> #include <stdlib.h> #include & invalid lvalue in assignment

  9. error: invalid lvalue in assignment

    A string literal is an *lvalue*; all other literals are *rvalues*. -4- The operator :: followed by an identifier, a qualified-id, or an operator-function-id is a primary-expression. Its type is specified by the

  10. :523: error: invalid lvalue in assignment

    If a cast can be done before the l-value and it produces a correct l-value, then it should be possible. This also means a cast to a non-pointer type. Technically, it might create a new, temporary variable as a result of the operation, but then again, it might not - it could be implemented either way.

  11. Please Help: 'invalid lvalue in assignment'

    Powers (incomplete).c:30: error: invalid lvalue in assignment C:\Documents and Settings\Chris Jordan\Desktop\C-prog Resit Coursework\6. Powers (incomplete).c:33: error: invalid lvalue in assignment C:\Documents and Settings\Chris Jordan\Desktop\C-prog Resit Coursework\6. Powers (incomplete).c:35: error: incompatible types in return. Execution ...

  12. error: invalid lvalue in assignment

    error: invalid lvalue in assignment. C / C++ Forums on Bytes. Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

  13. invalid lvalue

    gives "invalid lvalue in assignment" when compiled with the 64-bit Fedora Core 4 build of gcc 4.1.1. But it works fine with other versions of gcc, and other compilers, and the operation I want done looks entirely logical to me. Is this code C90-compliant or not? No. The result of a cast isn't a lvalue. see www.c-faq.com, question 4.5

  14. error: invalid lvalue in assignment

    I get error: invalid lvalue in assignment errors when trying to compile code with gcc 4.0+, this code previously compiled fine with gcc 3.x I'm not a c nor a c+ error: invalid lvalue in assignment - C - Tek-Tips

  15. Invalid lvalue in assignment when trying to advance a void-pointer

    -I openbsd-compat -I /usr/include -c common/common.c -o build/common.o common/common.c: In function 'transmit_iov': common/common.c:58: error: invalid lvalue in assignment My problem is that I have an array struct iovec iov[], which is: struct iovec {void *iov_base; /* Starting address */ size_t iov_len; /* Number of bytes */};

  16. Error: invalid lvalue in assignment

    m->next = newmsg; } else {. mod_msgs = newmsg; } which should be equivalent. "invalid lvalue" means the left-hand-side of an assignment (the lvalue) is messed up. It could be a gcc version issue as you surmised. Good luck, Jeff.

  17. c

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  18. invalid lvalue in assignment

    Invalid lvalue in assignment when trying to advance a void-pointer (struct iovec) by: A. Farber | last post by: Hello, I call readv() and writev() in several spots of a program which I run under Linux, OpenBSD and Cygwin.