• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

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.

What are the differences between "=" and "<-" assignment operators?

What are the differences between the assignment operators = and <- in R?

I know that operators are slightly different, as this example shows

But is this the only difference?

  • assignment-operator

user438383's user avatar

  • 68 As noted here the origins of the <- symbol come from old APL keyboards that actually had a single <- key on them. –  joran Commented Dec 12, 2014 at 17:35

9 Answers 9

The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:

In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

In this case, x is declared in the user workspace, so you can use it after the function call has been completed.

There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like

Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio ( Option + - under macOS), Shift + - (underscore) in emacs+ESS.

If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <- .

The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5 ?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.

To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3) .

Secondly, it's clearer if we use prefix notation for assignment. So

The parser interprets x <- y <- 5 as

We might expect that x <- y = 5 would then be

but actually it gets interpreted as

This is because = is lower precedence than <- , as shown on the ?Syntax help page.

Richie Cotton's user avatar

  • 14 This is also mentioned in chapter 8.2.26 of The R Inferno by Patrick Burns (Not me but a recommendation anyway) –  Uwe Commented Jun 14, 2016 at 9:17
  • 6 I just realised that your explanation of how x <- x = 5 gets interpreted is slightly wrong: In reality, R interprets it as ​`<-<-`(x, y = 5, value = 5) (which itself is more or less equivalent to tmp <- x; x <- `<-<-`(tmp, y = 5, value = 5) ). Yikes! –  Konrad Rudolph Commented Jul 27, 2018 at 11:25
  • 13 … And I just realised that the very first part of this answer is incorrect and, unfortunately, quite misleading because it perpetuates a common misconception: The way you use = in a function call does not perform assignment , and isn’t an assignment operator. It’s an entirely distinct parsed R expression, which just happens to use the same character. Further, the code you show does not “declare” x in the scope of the function. The function declaration performs said declaration. The function call doesn’t (it gets a bit more complicated with named ... arguments). –  Konrad Rudolph Commented Apr 12, 2019 at 10:33
  • 1 @ClarkThomborson The semantics are fundamentally different because in R assignment is a regular operation which is performed via a function call to an assignment function. However, this is not the case for = in an argument list. In an argument list, = is an arbitrary separator token which is no longer present after parsing. After parsing f(x = 1) , R sees (essentially) call("f", 1) . Whereas for x = 1 R sees call("=", "x", 1) . It's true that in both cases name binding also happens but, for the assignment operator, it happens after calling the assignment operator function. –  Konrad Rudolph Commented Jan 12, 2023 at 15:35
  • 1 At least in R version 4.2.2, median(x = 1:10) doesn't produce an error anymore. –  JAQuent Commented Dec 26, 2023 at 9:18

As your example shows, = and <- have slightly different operator precedence (which determines the order of evaluation when they are mixed in the same expression). In fact, ?Syntax in R gives the following operator precedence table, from highest to lowest:

… ‘-> ->>’ rightwards assignment ‘<- <<-’ assignment (right to left) ‘=’ assignment (right to left) …

Since you were asking about the assignment operators : yes, that is the only difference. However, you would be forgiven for believing otherwise. Even the R documentation of ?assignOps claims that there are more differences:

The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

Let’s not put too fine a point on it: the R documentation is wrong . This is easy to show: we just need to find a counter-example of the = operator that isn’t (a) at the top level, nor (b) a subexpression in a braced list of expressions (i.e. {…; …} ). — Without further ado:

Clearly we’ve performed an assignment, using = , outside of contexts (a) and (b). So, why has the documentation of a core R language feature been wrong for decades?

It’s because in R’s syntax the symbol = has two distinct meanings that get routinely conflated (even by experts, including in the documentation cited above):

  • The first meaning is as an assignment operator . This is all we’ve talked about so far.
  • The second meaning isn’t an operator but rather a syntax token that signals named argument passing in a function call. Unlike the = operator it performs no action at runtime, it merely changes the way an expression is parsed.

So how does R decide whether a given usage of = refers to the operator or to named argument passing? Let’s see.

In any piece of code of the general form …

… the = is the token that defines named argument passing: it is not the assignment operator. Furthermore, = is entirely forbidden in some syntactic contexts:

Any of these will raise an error “unexpected '=' in ‹bla›”.

In any other context, = refers to the assignment operator call. In particular, merely putting parentheses around the subexpression makes any of the above (a) valid, and (b) an assignment . For instance, the following performs assignment:

Now you might object that such code is atrocious (and you may be right). But I took this code from the base::file.copy function (replacing <- with = ) — it’s a pervasive pattern in much of the core R codebase.

The original explanation by John Chambers , which the the R documentation is probably based on, actually explains this correctly:

[ = assignment is] allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses.

In sum, by default the operators <- and = do the same thing. But either of them can be overridden separately to change its behaviour. By contrast, <- and -> (left-to-right assignment), though syntactically distinct, always call the same function. Overriding one also overrides the other. Knowing this is rarely practical but it can be used for some fun shenanigans .

Konrad Rudolph's user avatar

  • 5 About the precedence, and errors in R's doc, the precedence of ? is actually right in between = and <- , which has important consequences when overriding ? , and virtually none otherwise. –  moodymudskipper Commented Jan 10, 2020 at 0:12
  • 2 @Moody_Mudskipper that’s bizarre! You seem to be right, but according to the source code ( main/gram.y ), the precedence of ? is correctly documented, and is lower than both = and <- . –  Konrad Rudolph Commented Jan 10, 2020 at 10:13
  • 2 I like your explanation of R semantics... which I'd rephrase as follows. The "=" operator is overloaded. Its base semantics is to bind a formal name to an actual parameter in the arglist of a function call. In most (but not all!) contexts outside a function call, it has the same semantics as "<-": it binds a name to an existing object (or to a constant value), with copy-on-write semantics, with the side-effect of defining this name if it is currently undefined. In a few contexts, it is bound to stop() to warn naive or careless users who confuse it with the "==" operator. –  Clark Thomborson Commented Nov 24, 2022 at 2:50
  • 2 @ClarkThomborson I don't agree with calling one of the meanings the "base" semantics, because this implies a hierarchy that doesn't exist. And I think it's confusing to call = an overloaded operator, as well: the term "operator" in R has (until R 4.0, at least!) a specific meaning referring to a function call with special syntactic rules. This isn't what = is doing when used to bind a name to an parameter name inside a function call argument list. There's no call happening, so = in this context is just a syntactic token (like ; ), not an operator. –  Konrad Rudolph Commented Nov 24, 2022 at 10:17
  • 2 @ClarkThomborson Regardless of whether you find it helpful, that's precisely what it is: the syntactic = token for named parameters completely vanishes after the parsing phase, it isn't represented in the parse tree at all, nor is it evaluated. Name binding in assignment and in function calling happens fundamentally differently in R (and, to varying extents, in other languages), it isn't merely a "temporal distinction", nor is it due to operator precedence. –  Konrad Rudolph Commented Nov 24, 2022 at 15:33

Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice.

https://google.github.io/styleguide/Rguide.xml

The R manual goes into nice detail on all 5 assignment operators.

http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html

xxfelixxx's user avatar

  • 14 Note that any non-0 is considered TRUE by R. So if you intend to test if x is less than -y , you might write if (x<-y) which will not warn or error, and appear to work fine. It'll only be FALSE when y=0 , though. –  Matt Dowle Commented Jun 8, 2012 at 15:21
  • 53 Why hurt your eyes and finger with <- if you can use = ? In 99.99% of times = is fine. Sometimes you need <<- though, which is a different history. –  Fernando Commented Oct 9, 2013 at 1:22
  • 2 Besides the 0.01% which it won't work is just bad unreadable, hacky shortcut code for anyone who is not R only. It is just like doing bitshift to do a half division just to look smart (but you are not). My opinion is that R should deprecate the <- operator. –  caiohamamura Commented Oct 31, 2023 at 13:36

x = y = 5 is equivalent to x = (y = 5) , because the assignment operators "group" right to left, which works. Meaning: assign 5 to y , leaving the number 5; and then assign that 5 to x .

This is not the same as (x = y) = 5 , which doesn't work! Meaning: assign the value of y to x , leaving the value of y ; and then assign 5 to, umm..., what exactly?

When you mix the different kinds of assignment operators, <- binds tighter than = . So x = y <- 5 is interpreted as x = (y <- 5) , which is the case that makes sense.

Unfortunately, x <- y = 5 is interpreted as (x <- y) = 5 , which is the case that doesn't work!

See ?Syntax and ?assignOps for the precedence (binding) and grouping rules.

Steve Pitchers's user avatar

  • This was a succinct answer that hit the nail on the head! –  BroVic Commented Jun 4, 2023 at 16:03

According to John Chambers, the operator = is only allowed at "the top level," which means it is not allowed in control structures like if , making the following programming error illegal.

As he writes, "Disallowing the new assignment form [=] in control expressions avoids programming errors (such as the example above) that are more likely with the equal operator than with other S assignments."

You can manage to do this if it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses," so if ((x = 0)) 1 else x would work.

See http://developer.r-project.org/equalAssign.html

Aaron left Stack Overflow's user avatar

From the official R documentation :

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

Haim Evgi's user avatar

  • 12 I think "top level" means at the statement level, rather than the expression level. So x <- 42 on its own is a statement; in if (x <- 42) {} it would be an expression, and isn't valid. To be clear, this has nothing to do with whether you are in the global environment or not. –  Steve Pitchers Commented Sep 16, 2014 at 9:58
  • 1 This: “the operator = is only allowed at the top level” is a widely held misunderstanding and completely wrong. –  Konrad Rudolph Commented Mar 2, 2017 at 14:20
  • This is not true - for example, this works, even though assignment is not a complete expression: 1 + (x = 2) –  Pavel Minaev Commented Mar 5, 2017 at 22:52
  • 1 To clarify the comments by KonradRudolph and PavelMinaev, I think it's too strong to say that it's completely wrong, but there is an exception, which is when it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses." –  Aaron left Stack Overflow Commented Oct 15, 2019 at 13:57
  • 1 Or in function() x = 1 , repeat x = 1 , if (TRUE) x = 1 .... –  moodymudskipper Commented Jan 10, 2020 at 0:18

This may also add to understanding of the difference between those two operators:

For the first element R has assigned values and proper name, while the name of the second element looks a bit strange.

R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1

Scarabee's user avatar

I am not sure if Patrick Burns book R inferno has been cited here where in 8.2.26 = is not a synonym of <- Patrick states "You clearly do not want to use '<-' when you want to set an argument of a function.". The book is available at https://www.burns-stat.com/documents/books/the-r-inferno/

Diego's user avatar

  • 2 Yup, it has been mentioned . But the question is about the assignment operator , whereas your excerpt concerns the syntax for passing arguments. It should be made clear (because there’s substantial confusion surrounding this point) that this is not the assignment operator. –  Konrad Rudolph Commented Sep 6, 2021 at 17:27

There are some differences between <- and = in the past version of R or even the predecessor language of R (S language). But currently, it seems using = only like any other modern language (python, java) won't cause any problem. You can achieve some more functionality by using <- when passing a value to some augments while also creating a global variable at the same time but it may have weird/unwanted behavior like in

Highly recommended! Try to read this article which is the best article that tries to explain the difference between those two: Check https://colinfay.me/r-assignment/

Also, think about <- as a function that invisibly returns a value.

See: https://adv-r.hadley.nz/functions.html

Chunhui Gu's user avatar

  • Unfortuantely Colin Fay’s article (and now your answer) repeats the common misconception about the alleged difference between = and <- . The explanation is therefore incorrect. See my answer for an exhaustive correction of this pernicious falsehood. To make it explicit: you can rewrite your first code to use = instead of <- without changing its meaning: df <- data.frame(a = rnorm(10), (b = rnorm(10))) . And just like <- , =` is a function that invisibly returns a value. –  Konrad Rudolph Commented Jan 14, 2023 at 19:04
  • @Konrad Rudolph R uses some rules/principles when designing the language and code interpretation for efficiency and usability that not saw in other languages. I believe most people who ask the difference between = and <- is curious about why R has more than one assignment operator compared with other popular Science/math language such as Python. And whether I can safely just only use one = like in other languages. Besides, ( is also a function in R so technically (b = rnorm(10)) is not the same as b <- rnorm(10) since you can override the meaning of ( function in codes. –  Chunhui Gu Commented Jan 15, 2023 at 0:42
  • Yes that’s all true but what does this have to do with my comment? The answer to “why” is: “purely historical”, and the answer to “can I just use = ” is “yes”. Everything else, in particular your claim that = can’t be used in some cases, is incorrect . Yes, of course you can override ( , just like you can override = and <- so, yes, technically you can redefine them so that they are no longer identical. But surely you agree that this is a pure distraction. –  Konrad Rudolph Commented Jan 15, 2023 at 11:27

Not the answer you're looking for? Browse other questions tagged r assignment-operator r-faq or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags

Hot Network Questions

  • HTTP: how likely are you to be compromised by using it just once?
  • Personal Loan to a Friend
  • Can the Orient Express be motorized to run on standard track?
  • Monodromic but not equivariant sheaves and Braden's theorem
  • How can UserA programmatically replace a text string within a file they own that's located in /etc?
  • What does "the dogs of prescriptivism" mean?
  • Would a PhD from Europe, Canada, Australia, or New Zealand be accepted in the US?
  • The method of substitution in the problem of finding the integral
  • Raster Calculator - Batch Processing
  • How fast would unrest spread in the Middle Ages?
  • Old science fiction short story about a lawyer attempting to patent a new kind of incredibly strong cloth
  • A member of NATO falls into civil war, who do the rest of the members back?
  • Is there a category even more general than "thing"?
  • Clear jel to thicken the filling of a key lime pie?
  • Freewheeling diode in a capacitor
  • When should a function be given an argument vs getting the data itself?
  • Finding a paper that has only abstract on ADS
  • Finding reflexive, transitive closure
  • How to tell if the item language is the fallback language or the regular language version
  • Is there some sort of kitchen utensil/device like a cylinder with a strainer?
  • Looking for a caveman discovers fire short story that is a pun on "nuclear" power
  • RAW, do transparent obstacles generally grant Total Cover?
  • Vertical alignment of array inside array
  • Correct my understanding of Digital Signature Algorithm for TLS certificates?

assignment operator vs

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Share Your Experience

Assignment Operators in Programming

  • Arithmetic Operators in Programming
  • Binary Operators in Programming
  • Operator Associativity in Programming
  • C++ Assignment Operator Overloading
  • What are Operators in Programming?
  • Assignment Operators In C++
  • Bitwise AND operator in Programming
  • Increment and Decrement Operators in Programming
  • Types of Operators in Programming
  • Logical AND operator in Programming
  • Modulus Operator in Programming
  • Solidity - Assignment Operators
  • Augmented Assignment Operators in Python
  • Pre Increment and Post Increment Operator in Programming
  • JavaScript Assignment Operators
  • Operator Precedence and Associativity in Programming
  • Assignment Operators in Python
  • Assignment Operators in C
  • Subtraction Assignment( -=) Operator in Javascript
  • Coding for Everyone Course

Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.

Table of Content

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in C#
  • Assignment Operators in Javascript
  • Application of Assignment Operators

Assignment operators are used in programming to  assign values  to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign ( = ), which assigns the value on the right side of the operator to the variable on the left side.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

OperatorDescriptionExamples
= (Assignment)Assigns the value on the right to the variable on the left.  assigns the value 10 to the variable x.
+= (Addition Assignment)Adds the value on the right to the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
-= (Subtraction Assignment)Subtracts the value on the right from the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
*= (Multiplication Assignment)Multiplies the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
/= (Division Assignment)Divides the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
%= (Modulo Assignment)Calculates the modulo of the current value of the variable on the left and the value on the right, then assigns the result to the variable.  is equivalent to 

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.

Please Login to comment...

Similar reads.

  • Programming

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assignment operators

  • 8 contributors

expression assignment-operator expression

assignment-operator : one of   =   *=   /=   %=   +=   -=   <<=   >>=   &=   ^=   |=

Assignment operators store a value in the object specified by the left operand. There are two kinds of assignment operations:

simple assignment , in which the value of the second operand is stored in the object specified by the first operand.

compound assignment , in which an arithmetic, shift, or bitwise operation is performed before storing the result.

All assignment operators in the following table except the = operator are compound assignment operators.

Assignment operators table

Operator Meaning
Store the value of the second operand in the object specified by the first operand (simple assignment).
Multiply the value of the first operand by the value of the second operand; store the result in the object specified by the first operand.
Divide the value of the first operand by the value of the second operand; store the result in the object specified by the first operand.
Take modulus of the first operand specified by the value of the second operand; store the result in the object specified by the first operand.
Add the value of the second operand to the value of the first operand; store the result in the object specified by the first operand.
Subtract the value of the second operand from the value of the first operand; store the result in the object specified by the first operand.
Shift the value of the first operand left the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.
Shift the value of the first operand right the number of bits specified by the value of the second operand; store the result in the object specified by the first operand.
Obtain the bitwise AND of the first and second operands; store the result in the object specified by the first operand.
Obtain the bitwise exclusive OR of the first and second operands; store the result in the object specified by the first operand.
Obtain the bitwise inclusive OR of the first and second operands; store the result in the object specified by the first operand.

Operator keywords

Three of the compound assignment operators have keyword equivalents. They are:

Operator Equivalent

C++ specifies these operator keywords as alternative spellings for the compound assignment operators. In C, the alternative spellings are provided as macros in the <iso646.h> header. In C++, the alternative spellings are keywords; use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spelling.

Simple assignment

The simple assignment operator ( = ) causes the value of the second operand to be stored in the object specified by the first operand. If both objects are of arithmetic types, the right operand is converted to the type of the left, before storing the value.

Objects of const and volatile types can be assigned to l-values of types that are only volatile , or that aren't const or volatile .

Assignment to objects of class type ( struct , union , and class types) is performed by a function named operator= . The default behavior of this operator function is to perform a member-wise copy assignment of the object's non-static data members and direct base classes; however, this behavior can be modified using overloaded operators. For more information, see Operator overloading . Class types can also have copy assignment and move assignment operators. For more information, see Copy constructors and copy assignment operators and Move constructors and move assignment operators .

An object of any unambiguously derived class from a given base class can be assigned to an object of the base class. The reverse isn't true because there's an implicit conversion from derived class to base class, but not from base class to derived class. For example:

Assignments to reference types behave as if the assignment were being made to the object to which the reference points.

For class-type objects, assignment is different from initialization. To illustrate how different assignment and initialization can be, consider the code

The preceding code shows an initializer; it calls the constructor for UserType2 that takes an argument of type UserType1 . Given the code

the assignment statement

can have one of the following effects:

Call the function operator= for UserType2 , provided operator= is provided with a UserType1 argument.

Call the explicit conversion function UserType1::operator UserType2 , if such a function exists.

Call a constructor UserType2::UserType2 , provided such a constructor exists, that takes a UserType1 argument and copies the result.

Compound assignment

The compound assignment operators are shown in the Assignment operators table . These operators have the form e1 op = e2 , where e1 is a non- const modifiable l-value and e2 is:

an arithmetic type

a pointer, if op is + or -

a type for which there exists a matching operator *op*= overload for the type of e1

The built-in e1 op = e2 form behaves as e1 = e1 op e2 , but e1 is evaluated only once.

Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type, or it must be a constant expression that evaluates to 0. When the left operand is of an integral type, the right operand must not be of a pointer type.

Result of built-in assignment operators

The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

In ANSI C, the result of an assignment expression isn't an l-value. That means the legal C++ expression (a += b) += c isn't allowed in C.

Expressions with binary operators C++ built-in operators, precedence, and associativity C assignment operators

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

cppreference.com

Assignment operators.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
(C++11)
(C++26)

(C++11)
(C++11)
-expression
-expression
-expression
(C++11)
(C++11)
(C++17)
(C++20)
    

Assignment operators modify the value of the object.

Operator name  Syntax  Prototype examples (for class T)
Inside class definition Outside class definition
simple assignment Yes T& T::operator =(const T2& b);
addition assignment Yes T& T::operator +=(const T2& b); T& operator +=(T& a, const T2& b);
subtraction assignment Yes T& T::operator -=(const T2& b); T& operator -=(T& a, const T2& b);
multiplication assignment Yes T& T::operator *=(const T2& b); T& operator *=(T& a, const T2& b);
division assignment Yes T& T::operator /=(const T2& b); T& operator /=(T& a, const T2& b);
remainder assignment Yes T& T::operator %=(const T2& b); T& operator %=(T& a, const T2& b);
bitwise AND assignment Yes T& T::operator &=(const T2& b); T& operator &=(T& a, const T2& b);
bitwise OR assignment Yes T& T::operator |=(const T2& b); T& operator |=(T& a, const T2& b);
bitwise XOR assignment Yes T& T::operator ^=(const T2& b); T& operator ^=(T& a, const T2& b);
bitwise left shift assignment Yes T& T::operator <<=(const T2& b); T& operator <<=(T& a, const T2& b);
bitwise right shift assignment Yes T& T::operator >>=(const T2& b); T& operator >>=(T& a, const T2& b);

this, and most also return *this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including .
Definitions Assignment operator syntax Built-in simple assignment operator Assignment from an expression Assignment from a non-expression initializer clause Built-in compound assignment operator Example Defect reports See also

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in .

(since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

target-expr new-value (1)
target-expr op new-value (2)
target-expr - the expression to be assigned to
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
new-value - the expression (until C++11) (since C++11) to assign to the target
  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

If new-value is not an expression, the assignment expression will never match an overloaded compound assignment operator.

(since C++11)

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

If the type of target-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is a or an .

(since C++20)

new-value is only allowed not to be an expression in following situations:

is of a , and new-value is empty or has only one element. In this case, given an invented variable t declared and initialized as T t = new-value , the meaning of x = new-value  is x = t. is of class type. In this case, new-value is passed as the argument to the assignment operator function selected by .   <double> z; z = {1, 2}; // meaning z.operator=({1, 2}) z += {1, 2}; // meaning z.operator+=({1, 2})   int a, b; a = b = {1}; // meaning a = b = 1; a = {1} = b; // syntax error
(since C++11)

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

& operator=(T*&, T*);
volatile & operator=(T*volatile &, T*);

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

operator=(T&, T);

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

operator=(A1&, A2);

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

operator*=(A1&, A2);
operator/=(A1&, A2);
operator+=(A1&, A2);
operator-=(A1&, A2);

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

operator%=(I1&, I2);
operator<<=(I1&, I2);
operator>>=(I1&, I2);
operator&=(I1&, I2);
operator^=(I1&, I2);
operator|=(I1&, I2);

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

& operator+=(T*&, );
& operator-=(T*&, );
volatile & operator+=(T*volatile &, );
volatile & operator-=(T*volatile &, );

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++11 for assignments to class type objects, the right operand
could be an initializer list only when the assignment
is defined by a user-defined assignment operator
removed user-defined
assignment constraint
C++11 E1 = {E2} was equivalent to E1 = T(E2)
( is the type of ), this introduced a C-style cast
it is equivalent
to E1 = T{E2}
C++20 compound assignment operators for volatile
-qualified types were inconsistently deprecated
none of them
is deprecated
C++11 an assignment from a non-expression initializer clause
to a scalar value would perform direct-list-initialization
performs copy-list-
initialization instead
C++20 bitwise compound assignment operators for volatile types
were deprecated while being useful for some platforms
they are not
deprecated

[ edit ] See also

Operator precedence

Operator overloading

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[...]
*a
&a
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

for Assignment operators
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 23:41.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

What's the Difference Between the Assignment (`=`) and Equality (`==`, `===`) Operators?

assignment operator vs

.css-13lojzj{position:absolute;padding-right:0.25rem;margin-left:-1.25rem;left:0;height:100%;display:-webkit-inline-box;display:-webkit-inline-flex;display:-ms-inline-flexbox;display:inline-flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;display:none;} .css-b94zdx{width:1rem;height:1rem;} The Problem .css-1s1dm52{margin-left:1rem;}.css-1s1dm52.btn-small{font-size:0.8125rem;font-weight:500;height:auto;line-height:0.75rem;padding:0.5rem 0.75rem;} .css-vgbcnb{margin-left:1rem;}.css-vgbcnb.snackbar{height:auto;padding:0.5rem 0.75rem;}.css-vgbcnb.btn-small{font-size:0.8125rem;font-weight:500;height:auto;line-height:0.75rem;padding:0.5rem 0.75rem;} .css-16p7d4d{margin-left:1rem;}.css-16p7d4d.snackbar{height:auto;padding:0.5rem 0.75rem;}.css-16p7d4d.btn-small{font-size:0.8125rem;font-weight:500;height:auto;line-height:0.75rem;padding:0.5rem 0.75rem;} Jump To Solution

People who are new to programming often find it difficult to understand the difference between = , == , and === .

In mathematics we only use = , so what do the other two mean?

The Solution

The = is an assignment operator, while == and === are called equality operators.

Assignment Operator ( = )

In mathematics and algebra, = is an equal to operator. In programming = is an assignment operator , which means that it assigns a value to a variable.

For example, the following code will store a value of 5 in the variable x :

We can combine the declaration and assignment in one line:

It may look like the assignment operator works the same way as algebra’s equal to operator, but that’s not the case.

For example, the following doesn’t make any sense in algebra:

But it is acceptable in JavaScript (and other programming languages). JavaScript will take the expression on the right-hand side of the operator x + 4 and store this value in x again.

Equality Operator ( == )

In JavaScript, the operator that compares two values is written like this: == . It is called an equality operator . The equality operator is one of the many comparison operators in JavaScript that are used in logical and conditional statements.

The equality operator returns true or false based on whether the operands (the values being compared) are equal.

For example, the following code will return false :

Interestingly, if we compare an integer 5 and a string "5" it returns true .

That is because in most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for comparison. This behavior generally results in comparing the operands numerically.

Strict Equality Operator ( === )

Like the equality operator above, the strict equality operator compares the two values. But unlike the equality operator, the strict equality operator compares both the content and the type of the operands.

So using the strict equality operator, 5 and "5" are not equal.

It is better to use the strict equality operator to prevent type conversions, which may result in unexpected bugs. But if you’re certain the types on both sides will be the same, there is no problem with using the shorter operator.

  • Resources JavaScript Frontend Error Monitoring 101

Syntax.fm logo

Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

A peek at your privacy

Here’s a quick look at how Sentry handles your personal information (PII).

Who we collect PII from

We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.

What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.

PII we may collect about you

  • PII provided by you and related to your
  • Account, profile, and login
  • Requests and inquiries
  • PII collected from your device and usage
  • PII collected from third parties (e.g., social media)

How we use your PII

  • To operate our site and service
  • To protect and improve our site and service
  • To provide customer care and support
  • To communicate with you
  • For other purposes (that we inform you of at collection)

Third parties who receive your PII

We may disclose your PII to the following type of recipients:

  • Subsidiaries and other affiliates
  • Service providers
  • Partners (go-to-market, analytics)
  • Third-party platforms (when you connect them to our service)
  • Governmental authorities (where necessary)
  • An actual or potential buyer

We use cookies (but not for advertising)

  • We do not use advertising or targeting cookies
  • We use necessary cookies to run and improve our site and service
  • You can disable cookies but this can impact your use or access to certain parts of our site and service

Know your rights

You may have the following rights related to your PII:

  • Access, correct, and update
  • Object to or restrict processing
  • Opt-out of marketing
  • Be forgotten by Sentry
  • Withdraw your consent
  • Complain about us

If you have any questions or concerns about your privacy at Sentry, please email us at [email protected]

If you are a California resident, see our Supplemental notice .

21.12 — Overloading the assignment operator

Issues due to self-assignment

Fortunately, we can detect when self-assignment occurs. Here’s an updated implementation of our overloaded operator= for the MyString class:

When not to handle self-assignment

The copy and swap idiom

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

  • C - Getting Started
  • C - Overview
  • C - Advantages & Disadvantages
  • C - Character Set
  • Gcc Vs. G++
  • Why We should Use C?
  • C - Basic Rules
  • C - Comments
  • C - Variable Naming Conventions
  • C - Variable Initialization
  • C - Constants
  • C - Character Constant
  • C - Octal Literals
  • C - Hexadecimal Literals
  • C - Automatic (auto) Variables
  • Local Vs. Global Variables
  • C - Access Global Variables
  • Is exit() & return Statements are Same?
  • C - Print Float Value
  • C - Print Multiple Lines Using printf()
  • C - Argument Index Specification
  • C - Value Returned by scanf()
  • C - Returned Values of printf() & scanf()
  • What do 'lvalue' & 'rvalue' Mean
  • Automatic (auto) Vs. Static Variables

C Data Types

  • C - Data Types & Operators
  • C - Basic Data Types
  • C - 'unsigned char' For Memory Optimization
  • short Vs. short int Vs. int
  • unsigned int Vs. size_t
  • C - Storage Classes Introduction
  • C - Storage Classes With Examples
  • C- Type Conversion
  • C - Type Qualifiers

C Input/Output

  • C - Read String With Spaces
  • C - Input String of Unknown Length
  • C - Disadvantages of scanf()
  • C - scanf() need '%lf' for doubles, when printf() is okay with just '%f'
  • C - Format Specifier for unsigned short int
  • C - printf() Format Specifier for bool
  • C - printf() Arguments for long
  • C - printf() Specifier for double
  • Is there a printf() converter to print in binary format?
  • C - Nested printf()
  • printf() Vs. puts()
  • printf() Vs. sprintf()
  • %d Vs. %i format Specifiers
  • C - Single Character Input & Output
  • C- Formatted Input & Output
  • C - Octal & Hex Escape Sequences
  • C - Convert Float to String
  • gets() Vs. fgets()
  • C - Input Unsigned Integer Value
  • C - Input Octal Value
  • C - Input Hex Value
  • C - Input Decimal, Octal & Hex in char Variables
  • C - Input With '%i'
  • C - Input Individual Characters
  • C - Skip characters While Reading Integers
  • C - Read Memory Address
  • C - Printing Variable's Address
  • C - printf() Examples & Variations

C Operators

  • C - Operators Precedence & Associativity
  • Operators Vs. Operands
  • C - Unary Operators
  • C - Equality Operators
  • C - Logical AND (&&) Operator
  • C - Logical OR (||) Operator
  • C - Logical NOT (!) Operator
  • C - Modulus on Negative Numbers
  • C - Expression a=b=c (Multiple Assignment) Evaluates
  • C - Expression a==b==c (Multiple Comparison) Evaluates
  • C - Complex Return Statement Using Comma Operator
  • C - Comma Operator
  • C - Bitwise Operators
  • C - Bitwise One's Compliment
  • C - Modulus of Float or Double Numbers

C Conditional Statements

  • C - If Else Statements
  • C - Switch Case
  • C - Switch Statements Features, Disadvantages
  • C - Using Range With Switch

C Control Statements

  • C - 'goto' Statement
  • C - break & continue
  • Print Numbers From 1 to N Using goto
  • C - Looping
  • C - Looping Programs
  • C - Nested Loops
  • C - Entry Controlled Vs. Exit Controlled Loops
  • C - Sentinel Vs. Counter Controlled Loops
  • C - Use for Loop as Infinite Loop
  • C - Strings in C language programming
  • C - string.h Functions
  • C - memcpy() Function
  • C - Write Your Own memcpy()
  • C - memset() Function
  • C - Write Your Own memset()

C Functions

  • C - Library & User-define Functions
  • C - Static Functions
  • C - Scope of Function Parameters
  • C - Recursion
  • C - Recursion Examples
  • More on Arrays
  • C - Properties/Characteristics of Array

C Structure and Unions

  • C Structures
  • C - Initialize a Structure in Accordance
  • C - Size of Structure With No Members
  • C -Pointer to Structure
  • C - Nested Structure Initialization
  • C - Nested Structure With Examples
  • C - Size of Structure
  • C - Copy Complete Structure in Byte Array
  • C - Pointer to Union
  • C - Pointers
  • C - Pointer Rules
  • C - Pointers Declarations
  • C - Pointer Address Operators
  • C - Accessing Variable Using Pointer
  • C - Address of (&) & Dereference (*) Operators
  • C - NULL Pointer
  • C - Pointers as Argument
  • C - Pointer Arithmetic
  • C - Pointer to an Array
  • C - Evaluation of Statement '*ptr++'
  • C - Pointer & Non-pointer Variables Declarations Together
  • C - Pointer to an Array of Integers
  • C - Pointer to Pointer
  • C - void Pointer as Function Argument
  • char s[] Vs. char *s
  • C - Copying Integer Value to Char Buffer & Vice Versa
  • C - Call by Reference Vs. Call by Value
  • C - Typedef Function Pointer

C Preprocessor Directives

  • Recommendation for defining a macro in C language
  • Macro expansion directives (#define, #undef) in C language
  • Complex macro with arguments (function like macro) in C language
  • C language #ifdef, #else, #endif Pre-processor with Example
  • C language #if, #elif, #else, #endif Pre-processor with Example
  • Parameterized Macro - we cannot use space after the Macro Name
  • Stringizing Operator (#) in C
  • Token Pasting Directive Operator (##) in C

C Command-line Arguments

  • C language Command Line Arguments

C File Handlings

  • C - Basics of File Handling
  • C - File Handling Programs
  • C - Graphics Modes
  • C - Using Colors in Text Mode
  • C - More on Graphics Modes
  • C - OUTTEXTXY() & SETTEXTSTYLE() Functions
  • C - Draw Circle & Rectangle
  • C - graphics.h Functions
  • C - More Graphics-related Interesting Functions

C Advance Topics

  • C - Process Identification (pid_t)
  • C - getpid() & getppid()
  • C - Rrules For Writing C/C++ Program
  • C - Tips For Embedded Development
  • C - Optimization Techniques
  • C Vs. Embedded C
  • C- File Management System Calls
  • C/C++ Multithreading
  • C/C++ - Sum of Array Using Multithreading

C Tips and Tricks

  • C - Copy Two Bytes Int. to Byte Buffer
  • C - Is Pre-increment Faster than Post-increment?
  • C - Create Delay Function
  • Why should We use 'f' With Float Literal in C?
  • C - Replacing a Part of String
  • C- Comparing Number of Characters of Two Strings
  • C - Safest Way to Check Value Using ==
  • C- Check EVEN or ODD W/O % Operator
  • C- Use Single Byte to Store 8 Values
  • C- Funny Trick to Use C++ in C
  • C - Trick to Print Maximum Value of an unsigned int
  • C - Print Maximum Value of an unsigned int using One's Compliment (~) Operator in C
  • Why we should use switch instead of if else?
  • How to initialize array elements with hexadecimal values in C?
  • How should we declare/define a pointer variable?

C Important Topics

  • C - Working With Hexadecimal
  • C - Working With octal
  • C - Convert ASCII String (char[]) to BYTE Array
  • C - Convert ASCII String (char[]) to Octal String
  • C - Convert ASCII String (char[]) to Hex String
  • C - Assign Binary Calue in a Variable Directly
  • C - Check Particular Bit is SET or Not
  • C- Set, Clear, & Toggle a Bit
  • C - Value of 'EOF'
  • C - Print printf("Hello world."); Using printf()
  • C - Print Text in New Line w/O Using '\n'
  • C - Return 0 From int main()
  • 'Super Loop' Architecture for Embedded C
  • C - Executing System Commands
  • C - Infix To Postfix Conversion Using Stack
  • C - Evaluation of Postfix Expressions Using Stack
  • C - Polynomial Addition Using Structure
  • C - conio.h Functions
  • SQLite with C language
  • C - SQL Table Creation, Insertion
  • C - Aptitude Questions
  • C - Interview Questions
  • C - Find Output Programs

Home » C programming

What is the difference between = (Assignment) and == (Equal to) operators in C?

Difference between assignment (=) vs equal to (==) operators in c.

Many times this question arises what is the difference between = and == operators in C programming language? Here we are going to tell you exactly what the differences between these two operators are.

Assignment Operator (=)

= is an Assignment Operator in C, C++ and other programming languages, It is Binary Operator which operates on two operands.

= assigns the value of right side expression’s or variable’s value to the left side variable.

Let's understand by example:

Here, When first expression evaluates value of (a+b) will be assigned into x and in second expression y=x; value of variable x will be assigned into y .

Equal To Operator (==)

== is an Equal To Operator in C and C++ only, It is Binary Operator which operates on two operands.

== compares value of left and side expressions, return 1 if they are equal other will it will return 0.

When expression x==y evaluates, it will return 1 (it means condition is TRUE ) and "TRUE" will print.

So it's cleared now, , both are not same , = is an Assignment Operator it is used to assign the value of variable or expression, while == is an Equal to Operator and it is a relation operator used for comparison (to compare value of both left and right side operands).

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

IMAGES

  1. Chapter 3: Selection Structures: Making Decisions

    assignment operator vs

  2. Assignment Operator (=) VS Equal to Operator (==) || C Programming

    assignment operator vs

  3. Assignment Operator Vs Comparison Operator

    assignment operator vs

  4. Assignment Operator vs Equality Operator

    assignment operator vs

  5. Assignment Operator vs Equals to Operator

    assignment operator vs

  6. Difference Between Assignment Operator And 'Equal To' Operator, Computer Science Lecture

    assignment operator vs

VIDEO

  1. Operator VS Shorty #valorant

  2. Navy Operator VS. Goon Culture #shorts

  3. Operator Vs shotgunner

  4. Operator vs Marshal #valorant #shorts

  5. JavaScript Logical Operator & Assignment Operator

  6. 134 Part 1 Writing assignment operator and copy constructor

COMMENTS

  1. What are the differences between "=" and "<-" assignment ...

    Name binding in assignment and in function calling happens fundamentally differently in R (and, to varying extents, in other languages), it isn't merely a "temporal distinction", nor is it due to operator precedence.

  2. What is the difference between = (Assignment) and == (Equal ...

    a and b are not equal. The differences can be shown in tabular form as follows: =. ==. It is an assignment operator. It is a relational or comparison operator. It is used for assigning the value to a variable. It is used for comparing two values. It returns 1 if both the values are equal otherwise returns 0.

  3. Copy Constructor vs Assignment Operator in C++ - GeeksforGeeks

    Last Updated : 10 May, 2022. Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them: Consider the following C++ program. CPP. // CPP Program to demonstrate the use of copy constructor. // and assignment operator. #include <iostream>

  4. Assignment Operators in Programming - GeeksforGeeks

    What are Assignment Operators? Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data.

  5. Assignment operators | Microsoft Learn

    Assignment operators store a value in the object specified by the left operand. There are two kinds of assignment operations: simple assignment , in which the value of the second operand is stored in the object specified by the first operand.

  6. Assignment operators - cppreference.com

    Built-in compound assignment operator. The behavior of every built-in compound-assignment expression target-expr op  = new-value is exactly the same as the behavior of the expression target-expr = target-expr op new-value, except that target-expr is evaluated only once.

  7. Assignment (=) - JavaScript | MDN - MDN Web Docs

    The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

  8. What's the Difference Between the Assignment ... - Sentry

    The Solution. The = is an assignment operator, while == and === are called equality operators. Assignment Operator ( =) In mathematics and algebra, = is an equal to operator. In programming = is an assignment operator, which means that it assigns a value to a variable. For example, the following code will store a value of 5 in the variable x:

  9. Overloading the assignment operator – Learn C++">21.12 — Overloading the assignment operator – Learn C++

    Overloading the copy assignment operator (operator=) is fairly straightforward, with one specific caveat that we’ll get to. The copy assignment operator must be overloaded as a member function.

  10. Difference between = (Assignment) and == (Equal to) operators ...">Difference between = (Assignment) and == (Equal to) operators ...

    So it's cleared now, , both are not same, = is an Assignment Operator it is used to assign the value of variable or expression, while == is an Equal to Operator and it is a relation operator used for comparison (to compare value of both left and right side operands). Learn & Test Your Skills.