cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

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

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 must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

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

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

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

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:

[ 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:

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:

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

[ edit ] Example

Possible output:

[ edit ] Defect reports

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

[ edit ] See also

Operator precedence

Operator overloading

  • 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 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Home » Learn C Programming from Scratch » C Assignment Operators

C Assignment Operators

Summary : in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.

Introduction to the C assignment operators

An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:

After the assignmment, the counter variable holds the number 1.

The following example adds 1 to the counter and assign the result to the counter:

The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.

Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

The following example uses a compound-assignment operator (+=):

The expression:

is equivalent to the following expression:

The following table illustrates the compound-assignment operators in C:

  • A simple assignment operator assigns the value of the left operand to the right operand.
  • A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.
  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

A complete and detailed list of operators and expressions is also available in the reference .

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

  • Assignment operators
  • Comparison operators
  • Arithmetic operators
  • Bitwise operators

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3+4 or x*y .

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x .

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Note:  ( => ) is not an operator, but the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer: Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation).

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

The shift operators are listed in the following table.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) simply evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

The fourth form is legal only within a with statement, to delete a property from an object.

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

If the delete operator succeeds, it sets the property or element to undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

When you delete an array element, the array length is not affected. For example, if you delete a[3] , a[4] is still a[4] and a[3] is undefined.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete . However, trees[3] is still addressable and returns undefined .

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined , but the array element still exists:

The typeof operator is used in either of the following ways:

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator is used in either of the following ways:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined , which has no effect in JavaScript.

The following code creates a hypertext link that submits a form when the user clicks it.

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference .

  • Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluates and therefore resolves to value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable. JavaScript has the following expression categories:

  • Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators .)
  • String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators .)
  • Logical: evaluates to true or false. (Often involves logical operators .)
  • Primary expressions: Basic keywords and general expressions in JavaScript.
  • Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

  • Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

Comprehensions

Comprehensions are an experimental JavaScript feature, targeted to be included in a future ECMAScript version. There are two versions of comprehensions:

Comprehensions exist in many programming languages and allow you to quickly assemble a new array based on an existing one, for example.

Left values are the destination of an assignment.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Similarly, the spread operator works with function calls:

Document Tags and Contributors

  • l10n:priority
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

4.6: Assignment Operator

  • Last updated
  • Save as PDF
  • Page ID 29038

  • Patrick McClanahan
  • San Joaquin Delta College

Assignment Operator

The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol. But bite your tongue, when you see the = symbol you need to start thinking: assignment. The assignment operator has two operands. The one to the left of the operator is usually an identifier name for a variable. The one to the right of the operator is a value.

The value 21 is moved to the memory location for the variable named: age. Another way to say it: age is assigned the value 21.

The item to the right of the assignment operator is an expression. The expression will be evaluated and the answer is 14. The value 14 would assigned to the variable named: total_cousins.

The expression to the right of the assignment operator contains some identifier names. The program would fetch the values stored in those variables; add them together and get a value of 44; then assign the 44 to the total_students variable.

As we have seen, assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below:

  • “=” : This is the simplest assignment operator, which was discussed above. This operator is used to assign the value on the right to the variable on the left. For example: a = 10; b = 20; ch = 'y';

If initially the value 5 is stored in the variable a,  then:  (a += 6) is equal to 11.  (the same as: a = a + 6)

If initially value 8 is stored in the variable a, then (a -= 6) is equal to  2. (the same as a = a - 6)

If initially value 5 is stored in the variable a,, then (a *= 6) is equal to 30. (the same as a = a * 6)

If initially value 6 is stored in the variable a, then (a /= 2) is equal to 3. (the same as a = a / 2)

Below example illustrates the various Assignment Operators:

Definitions

 Adapted from:  "Assignment Operator"  by  Kenneth Leroy Busbee , (Download for free at http://cnx.org/contents/[email protected] ) is licensed under  CC BY 4.0

  • Skip to main content
  • Select language
  • Skip to search
  • Add a translation
  • Print this page
  • Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand.

The basic assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x . The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

Simple assignment operator which assigns a value to a variable. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example.

Addition assignment

The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.

Subtraction assignment

The subtraction assignment operator subtracts the value of the right operand from a variable and assigns the result to the variable. See the subtraction operator for more details.

Multiplication assignment

The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

Division assignment

The division assignment operator divides a variable by the value of the right operand and assigns the result to the variable. See the division operator for more details.

Remainder assignment

The remainder assignment operator divides a variable by the value of the right operand and assigns the remainder to the variable. See the remainder operator for more details.

Left shift assignment

The left shift assignment operator moves the specified amount of bits to the left and assigns the result to the variable. See the left shift operator for more details.

Right shift assignment

The right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the right shift operator for more details.

Unsigned right shift assignment

The unsigned right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the unsigned right shift operator for more details.

Bitwise AND assignment

The bitwise AND assignment operator uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable. See the bitwise AND operator for more details.

Bitwise XOR assignment

The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable. See the bitwise XOR operator for more details.

Bitwise OR assignment

The bitwise OR assignment operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable. See the bitwise OR operator for more details.

Left operand with another assignment operator

In unusual situations, the assignment operator (e.g. x += y ) is not identical to the meaning expression (here x = x + y ). When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

Specifications

Browser compatibility.

  • Arithmetic operators

Document Tags and Contributors

  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • JavaScript basics
  • JavaScript technologies overview
  • Introduction to Object Oriented JavaScript
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • Standard built-in objects
  • ArrayBuffer
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread operator
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Statements and declarations
  • Legacy generator function
  • for each...in
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template strings
  • Deprecated features
  • New in JavaScript
  • ECMAScript 5 support in Mozilla
  • ECMAScript 6 support in Mozilla
  • ECMAScript 7 support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • C - Functions
  • C - Main Functions
  • C - Return Statement
  • C - Recursion
  • C - Scope Rules
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • C - Pointers
  • C - Pointer Arithmetics
  • C - Passing Pointers to Functions
  • C - Strings
  • C - Array of Strings
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Pointers to Structures
  • C - Self-Referential Structures
  • C - Nested Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Assignment Operators in C

In C, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable or an expression. The value to be assigned forms the right hand operand, whereas the variable to be assigned should be the operand to the left of = symbol, which is defined as a simple assignment operator in C. In addition, C has several augmented assignment operators.

The following table lists the assignment operators supported by the C language −

Simple assignment operator (=)

The = operator is the most frequently used operator in C. As per ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed. You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.

You can use a literal, another variable or an expression in the assignment statement.

Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error.

In C, the expressions that refer to a memory location are called "lvalue" expressions. A lvalue may appear as either the left-hand or right-hand side of an assignment.

On the other hand, the term rvalue refers to a data value that is stored at some address in memory. A rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

Augmented assignment operators

In addition to the = operator, C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining arithmetic or bitwise operation with assignment.

For example, the expression a+=b has the same effect of performing a+b first and then assigning the result back to the variable a.

Similarly, the expression a<<=b has the same effect of performing a<<b first and then assigning the result back to the variable a.

Here is a C program that demonstrates the use of assignment operators in C:

When you compile and execute the above program, it produces the following result −

  • RecentChanges

Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.

Precedence And Associativity

Consider an expression describable by the representation below, where both OP1 and OP2 are fill-in-the-blanks for OPerators.

The combination above has two possible interpretations:

Which one the language decides to adopt depends on the identity of OP1 and OP2 .

If OP1 and OP2 have different precedence levels (see the table below), the operator with the higher precedence goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.

Within operators of the same precedence, the language groups them by associativity . Left-associativity (left-to-right) means that it is interpreted as (a OP1 b) OP2 c , while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c) . Assignment operators are right-associative, so you can write:

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5 — the return value of b = 5 , a.k.a. right operand of the assignment.

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.

Operators are first grouped by precedence, and then, for adjacent operators that have the same precedence, by associativity. So, when mixing division and exponentiation, the exponentiation always comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2) .

For prefix unary operators, suppose we have the following pattern:

where OP1 is a prefix unary operator and OP2 is a binary operator. If OP1 has higher precedence than OP2 , then it would be grouped as (OP1 a) OP2 b ; otherwise, it would be OP1 (a OP2 b) .

If the unary operator is on the second operand:

Then the binary operator OP2 must have lower precedence than the unary operator OP1 for it to be grouped as a OP2 (OP1 b) . For example, the following is invalid:

Because + has higher precedence than yield , this would become (a + yield) 1 — but because yield is a reserved word in generator functions, this would be a syntax error. Luckily, most unary operators have higher precedence than binary operators and do not suffer from this pitfall.

If we have two prefix unary operators:

Then the unary operator closer to the operand, OP2 , must have higher precedence than OP1 for it to be grouped as OP1 (OP2 a) . It's possible to get it the other way and end up with (OP1 OP2) a :

Because await has higher precedence than yield , this would become (await yield) 1 , which is awaiting an identifier called yield , and a syntax error. Similarly, if you have new !A; , because ! has lower precedence than new , this would become (new !) A , which is obviously invalid. (This code looks nonsensical to write anyway, since !A always produces a boolean, not a constructor function.)

For postfix unary operators (namely, ++ and -- ), the same rules apply. Luckily, both operators have higher precedence than any binary operator, so the grouping is always what you would expect. Moreover, because ++ evaluates to a value , not a reference , you can't chain multiple increments together either, as you may do in C.

Operator precedence will be handled recursively . For example, consider this expression:

First, we group operators with different precedence by decreasing levels of precedence.

  • The ** operator has the highest precedence, so it's grouped first.
  • Looking around the ** expression, it has * on the right and + on the left. * has higher precedence, so it's grouped first. * and / have the same precedence, so we group them together for now.
  • Looking around the * / / expression grouped in 2, because + has higher precedence than >> , the former is grouped.

Within the * / / group, because they are both left-associative, the left operand would be grouped.

Note that operator precedence and associativity only affect the order of evaluation of operators (the implicit grouping), but not the order of evaluation of operands . The operands are always evaluated from left-to-right. The higher-precedence expressions are always evaluated first, and their results are then composed according to the order of operator precedence.

If you are familiar with binary trees, think about it as a post-order traversal .

After all operators have been properly grouped, the binary operators would form a binary tree. Evaluation starts from the outermost group — which is the operator with the lowest precedence ( / in this case). The left operand of this operator is first evaluated, which may be composed of higher-precedence operators (such as a call expression echo("left", 4) ). After the left operand has been evaluated, the right operand is evaluated in the same fashion. Therefore, all leaf nodes — the echo() calls — would be visited left-to-right, regardless of the precedence of operators joining them.

Short-circuiting

In the previous section, we said "the higher-precedence expressions are always evaluated first" — this is generally true, but it has to be amended with the acknowledgement of short-circuiting , in which case an operand may not be evaluated at all.

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c) , if a is , then the sub-expression (b + c) will not even get evaluated, even if it is grouped and therefore has higher precedence than && . We could say that the logical AND operator ( && ) is "short-circuited". Along with logical AND, other short-circuited operators include logical OR ( || ), nullish coalescing ( ?? ), and optional chaining ( ?. ).

When evaluating a short-circuited operator, the left operand is always evaluated. The right operand will only be evaluated if the left operand cannot determine the result of the operation.

Note: The behavior of short-circuiting is baked in these operators. Other operators would always evaluate both operands, regardless if that's actually useful — for example, NaN * foo() will always call foo , even when the result would never be something other than NaN .

The previous model of a post-order traversal still stands. However, after the left subtree of a short-circuiting operator has been visited, the language will decide if the right operand needs to be evaluated. If not (for example, because the left operand of || is already truthy), the result is directly returned without visiting the right subtree.

Consider this case:

Only C() is evaluated, despite && having higher precedence. This does not mean that || has higher precedence in this case — it's exactly because (B() && A()) has higher precedence that causes it to be neglected as a whole. If it's re-arranged as:

Then the short-circuiting effect of && would only prevent C() from being evaluated, but because A() && C() as a whole is false , B() would still be evaluated.

However, note that short-circuiting does not change the final evaluation outcome. It only affects the evaluation of operands , not how operators are grouped — if evaluation of operands doesn't have side effects (for example, logging to the console, assigning to variables, throwing an error), short-circuiting would not be observable at all.

The assignment counterparts of these operators ( &&= , ||= , ??= ) are short-circuited as well. They are short-circuited in a way that the assignment does not happen at all.

The following table lists operators in order from highest precedence (18) to lowest precedence (1).

Several notes about the table:

  • Not all syntax included here are "operators" in the strict sense. For example, spread ... and arrow => are typically not regarded as operators. However, we still included them to show how tightly they bind compared to other operators/expressions.
  • The left operand of an exponentiation ** (precedence 13) cannot be one of the unary operators with precedence 14 without grouping, or there will be a SyntaxError . That means, although -1 ** 2 is technically unambiguous, the language requires you to use (-1) ** 2 instead.
  • The operands of nullish coalescing ?? (precedence 3) cannot be a logical OR || (precedence 3) or logical AND && (precedence 4). That means you have to write (a ?? b) || c or a ?? (b || c) , instead of a ?? b || c .
  • Some operators have certain operands that require expressions narrower than those produced by higher-precedence operators. For example, the right-hand side of member access . (precedence 17) must be an identifier instead of a grouped expression. The left-hand side of arrow => (precedence 2) must be an arguments list or a single identifier instead of some random expression.
  • Some operators have certain operands that accept expressions wider than those produced by higher-precedence operators. For example, the bracket-enclosed expression of bracket notation [ … ] (precedence 17) can be any expression, even comma (precedence 1) joined ones. These operators act as if that operand is "automatically grouped". In this case we will omit the associativity.

C Programming Tutorial

  • Assignment Operator in C

Last updated on July 27, 2020

We have already used the assignment operator ( = ) several times before. Let's discuss it here in detail. The assignment operator ( = ) is used to assign a value to the variable. Its general format is as follows:

The operand on the left side of the assignment operator must be a variable and operand on the right-hand side must be a constant, variable or expression. Here are some examples:

The precedence of the assignment operator is lower than all the operators we have discussed so far and it associates from right to left.

We can also assign the same value to multiple variables at once.

here x , y and z are initialized to 100 .

Since the associativity of the assignment operator ( = ) is from right to left. The above expression is equivalent to the following:

Note that expressions like:

are called assignment expression. If we put a semicolon( ; ) at the end of the expression like this:

then the assignment expression becomes assignment statement.

Compound Assignment Operator #

Assignment operations that use the old value of a variable to compute its new value are called Compound Assignment.

Consider the following two statements:

Here the second statement adds 5 to the existing value of x . This value is then assigned back to x . Now, the new value of x is 105 .

To handle such operations more succinctly, C provides a special operator called Compound Assignment operator.

The general format of compound assignment operator is as follows:

where op can be any of the arithmetic operators ( + , - , * , / , % ). The above statement is functionally equivalent to the following:

Note : In addition to arithmetic operators, op can also be >> (right shift), << (left shift), | (Bitwise OR), & (Bitwise AND), ^ (Bitwise XOR). We haven't discussed these operators yet.

After evaluating the expression, the op operator is then applied to the result of the expression and the current value of the variable (on the RHS). The result of this operation is then assigned back to the variable (on the LHS). Let's take some examples: The statement:

is equivalent to x = x + 5; or x = x + (5); .

Similarly, the statement:

is equivalent to x = x * 2; or x = x * (2); .

Since, expression on the right side of op operator is evaluated first, the statement:

is equivalent to x = x * (y + 1) .

The precedence of compound assignment operators are same and they associate from right to left (see the precedence table ).

The following table lists some Compound assignment operators:

The following program demonstrates Compound assignment operators in action:

Expected Output:

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

MarketSplash

Mastering The Art Of Assignment: Exploring C Assignment Operators

Dive into the world of C Assignment Operators in our extensive guide. Understand the syntax, deep-dive into variables, and explore complex techniques and practical applications.

💡 KEY INSIGHTS

  • Assignment operators in C are not just for basic value assignment; they enable simultaneous arithmetic operations, enhancing code efficiency and readability.
  • The article emphasizes the importance of understanding operator precedence in C, as misinterpretation can lead to unexpected results, especially with compound assignment operators.
  • Common mistakes like confusing assignment with equality ('=' vs '==') are highlighted, offering practical advice for avoiding such pitfalls in C programming.
  • The guide provides real-world analogies for each assignment operator, making complex concepts more relatable and easier to grasp for programmers.
Welcome, bold programmers and coding enthusiasts! Let's set the stage: you're at your desk, fingers hovering over the keyboard, ready to embark on a journey deep into the belly of C programming. You might be wondering, why do I need to know about these 'assignment operators'?

Well, imagine trying to build a house with a toolbox that only has a hammer. You could probably make something that vaguely resembles a house, but without a screwdriver, wrench, or saw, it's going to be a bit...wobbly. This, my friends, is the importance of understanding operators in C. They're like the indispensable tools in your coding toolbox. And today, we're honing in on the assignment operators .

Now, our mission, should we choose to accept it, is to delve into the world of assignment operators in C. Like secret agents discovering the inner workings of a villain's lair, we're going to uncover the secrets that these '=' or '+=' symbols hold.

To all the night owls out there, I see you, and I raise you an operator. Just like how a cup of coffee (or three) helps us conquer that midnight oil, mastering operators in C can transform your coding journey from a groggy stumble to a smooth sprint.

But don't just take my word for it. Let's take a real-world example. Imagine you're coding a video game. You need your character to jump higher each time they collect a power-up. Without assignment operators, you'd be stuck adding numbers line by line. But with the '+=' operator, you can simply write 'jumpHeight += powerUpBoost,' and your code becomes a thing of elegance. It's like going from riding a tricycle to a high-speed motorbike.

In this article, we're going to unpack, examine, and get intimately acquainted with these assignment operators. We'll reveal their secrets, understand their behaviors, and learn how to use them effectively to power our C programming skills to new heights. Let's strap in, buckle up, and get ready for takeoff into the cosmic realms of C assignment operators!

The Basics Of C Operators

Deep dive into assignment operators in c, detailed exploration of each assignment operator, common use cases of assignment operators, common mistakes and how to avoid them, practice exercises, references and further reading.

Alright, get ready to pack your mental suitcase as we prepare to embark on the grand tour of C operators. We'll be stopping by the various categories, getting to know the locals (the operators, that is), and understanding how they contribute to the vibrant community that is a C program.

What Are Operators In C?

Operators in C are like the spicy condiments of coding. Without them, you'd be left with a bland dish—or rather, a simple list of variables. But splash on some operators, and suddenly you've got yourself an extravagant, dynamic, computational feast. In technical terms, operators are special symbols that perform specific operations on one, two, or three operands, and then return a result . They're the magic sauce that allows us to perform calculations, manipulate bits, and compare data.

Categories Of Operators In C

Now, just as you wouldn't use hot sauce on your ice cream (unless that's your thing), different operators serve different purposes. C language has been generous enough to provide us with a variety of operator categories, each with its distinct charm and role.

Let's break it down:

Imagine you're running a pizza shop. The arithmetic operators are like your basic ingredients: cheese, sauce, dough. They form the foundation of your pizza (program). But then you want to offer different pizza sizes. That's where your relational operators come in, comparing the diameter of small, medium, and large pizzas.

You're going well, but then you decide to offer deals. Buy two pizzas, get one free. Enter the logical operators , evaluating whether the conditions for the deal have been met. And finally, you want to spice things up with some exotic ingredients. That's your bitwise operators , working behind the scenes, adding that unique flavor that makes your customers keep coming back.

However, today, we're going to focus on a particular subset of the arithmetic operators: the assignment operators . These are the operators that don't just make the pizza but ensure it reaches the customer's plate (or in this case, the right variable).

Next up: We explore these unsung heroes of the programming world, toasting their accomplishments and discovering their capabilities. So, hold onto your hats and glasses, folks. This here's the wildest ride in the coding wilderness!

Prepare your diving gear and adjust your oxygen masks, friends, as we're about to plunge deep into the ocean of C programming. Hidden in the coral reef of code, you'll find the bright and beautiful creatures known as assignment operators.

What Are Assignment Operators?

In the broad ocean of C operators, the assignment operators are the dolphins - intelligent, adaptable, and extremely useful. On the surface, they may appear simple, but don't be fooled; these creatures are powerful. They have the capability to not only assign values to variables but also perform arithmetic operations concurrently.

The basic assignment operator in C is the '=' symbol. It's like the water of the ocean, essential to life (in the world of C programming). But alongside this staple, we have a whole family of compound assignment operators including '+=', '-=', '*=', '/=', and '%='. These are the playful dolphins leaping out of the water, each adding their unique twist to the task of assignment.

Syntax And Usage Of Assignment Operators

Remember, even dolphins have their ways of communicating, and so do assignment operators. They communicate through their syntax. The syntax for assignment operators in C follows a simple pattern:

In this dance, the operator and the '=' symbol perform a duet, holding onto each other without a space in between. They're the dancing pair that adds life to the party (aka your program).

Let's say you've won the lottery (congratulations, by the way!) and you want to divide your winnings between your three children. You could write out the arithmetic long-hand, or you could use the '/=' operator to streamline your process:

Just like that, your winnings are divided evenly, no calculator required.

List Of Assignment Operators In C

As promised, let's get to know the whole family of assignment operators residing in the C ocean:

Alright, we've taken the plunge and gotten our feet wet (or fins, in the case of our dolphin friends). But the dive is far from over. Next up, we're going to swim alongside each of these assignment operators, exploring their unique behaviors and abilities in the wild, vibrant world of C programming. So, keep your scuba gear on and get ready for more underwater adventure!

Welcome back, dear diver! Now that we've acquainted ourselves with the beautiful pod of dolphins, aka assignment operators, it's time to learn about each dolphin individually. We're about to uncover their quirks, appreciate their styles, and recognize their talents.

The Simple Assignment Operator '='

Let's start with the leader of the pack: the '=' operator. This unassuming symbol is like the diligent mail carrier, ensuring the right packages (values) get to the correct houses (variables).

Take a look at this:

In this code snippet, '=' ensures that the value '5' gets assigned to the variable 'chocolate'. Simple as that. No muss, no fuss, just a straightforward delivery of value.

The Addition Assignment Operator '+='

Next, we have the '+=' operator. This operator is a bit like a friendly baker. He takes what he has, adds more ingredients, and gives you the result - a delicious cake! Or, in this case, a new value.

Consider this:

We started with 12 doughnuts. But oh look, a friend dropped by with 3 more! So we add those to our box, and now we have 15. The '+=' operator made that addition quick and easy.

The Subtraction Assignment Operator '-='

Following the '+=' operator, we have its twin but with a different personality - the '-=' operator. If '+=' is the friendly baker, then '-=' is the weight-conscious friend who always removes extra toppings from their pizza. They take away rather than add.

For instance:

You've consumed 2000 calories today, but then you went for a run and burned 500. The '-=' operator is there to quickly update your calorie count.

The Multiplication Assignment Operator '*='

Say hello to the '*=' operator. This one is like the enthusiastic party planner who multiplies the fun! They take your initial value and multiply it with another, bringing more to the table.

Check this out:

You're at a level 7 excitement about your upcoming birthday, but then you learn that your best friend is flying in to celebrate with you. Your excitement level just doubled, and '*=' is here to make that calculation easy.

The Division Assignment Operator '/='

Here's the '/=' operator, the calm and composed yoga teacher of the group. They're all about division and balance. They take your original value and divide it by another, bringing harmony to your code.

You're pretty anxious about your job interview - let's say a level 10 anxiety. But then you do some deep breathing exercises, which helps you halve your anxiety level. The '/=' operator helps you reflect that change in your code.

The Modulus Assignment Operator '%='

Finally, we meet the quirky '%=' operator, the mystery novelist of the group. They're not about the whole story but the remainder, the leftovers, the little details others might overlook.

Look at this:

You have 10 books to distribute equally among your 3 friends. Everyone gets 3, and you're left with 1 book. The '%=' operator is there to quickly calculate that remainder for you.

That's the end of our detailed exploration. I hope this underwater journey has provided you with a greater appreciation and understanding of these remarkable creatures. Remember, each operator, like a dolphin, has its unique abilities, and knowing how to utilize them effectively can greatly enhance your programming prowess.

Now, let's swerve away from the theoretical and deep-dive into the practical. After all, C assignment operators aren't just sparkling little seashells you collect and admire. They're more like versatile tools in your programming Swiss Army knife. So, let's carve out some real-world use cases for our cherished assignment operators.

Variable Initialization And Value Change

Assignment operators aren't just for show; they've got some moves. Take our plain and humble '='. It's the bread-and-butter operator used in variable initialization and value changes, helping your code be as versatile as a chameleon.

In this scenario, our friend '=' is doing double duty—initializing 'a' with the value 10 and then changing it to 20. Not flashy, but oh-so-vital.

Calculation Updates In Real-Time Applications

Assignment operators are like those awesome, multitasking waitstaff you see in busy restaurants, juggling multiple tables and orders while still managing to serve everyone with a smile. They are brilliant when you want to perform real-time updates to your data.

In this scenario, '+=' and '-=' are the maitre d' of our code-restaurant, updating the user's balance with each buy or sell order.

Running Totals And Averages

Assignment operators are great runners - they don't tire and always keep the tally running.

Here, the '+=' and '-=' operators keep a running tally of points, allowing the system to adjust to the ebbs and flows of the school year like a seasoned marathon runner pacing themselves.

Iterations In Loop Constructs

The '*=' and '/=' operators often lurk within loop constructs, handling iterations with the grace of a prima ballerina. They're the choreographers of your loops, making sure each iteration flows seamlessly into the next.

In this case, '/=' is the elegant dancer gracefully halving 'i' with each twirl across the dance floor (iteration).

Working With Remainders

And let's not forget our mysterious '%=', the detective of the bunch, always searching for the remainder, the evidence left behind.

Here, '%=' is the sleuth, determining whether a number is even or odd by examining the remainder when divided by 2.

So, these are just a few examples of how assignment operators flex their muscles in the real world. They're like superheroes, each with their unique powers, ready to assist you in writing clean, efficient, and understandable code. Use them wisely, and your code will be as smooth as a well-choreographed ballet.

Let's face it, even the best of us trip over our own feet sometimes. And when it comes to assignment operators in C, there are some pitfalls that could make you stumble. But don't worry! We've all been there. Let's shed some light on these common mistakes so we can step over them with the grace of a ballet dancer leaping over a pit of snapping alligators.

Confusing Assignment With Equality

A surprisingly common misstep is confusing the assignment operator '=' with the equality operator '=='. It's like mixing up salt with sugar while baking. Sure, they might look similar, but one will definitely not sweeten your cake.

In this snippet, instead of checking if 'a' equals 10, we've assigned 'a' the value 10. The compiler will happily let this pass and might even give you a standing ovation for your comedy of errors. The correct approach?

Overlooking Operator Precedence

C operators are a bit like the characters in "Game of Thrones." They've got a complex hierarchy and they respect the rule of precedence. Sometimes, this can lead to unexpected results. For instance, check out this bit of misdirection:

Here, '/=' doesn't immediately divide 'a' by 2. It waits for the multiplication to happen (due to operator precedence), and then performs the operation. So it's actually doing a /= (2*5), not (a/=2)*5. It's like arriving late to a party and finding out all the pizza is gone. To ensure you get your slice, use parentheses:

Misusing Modulo With Floats

Ah, the modulo operator, always looking for the remainder. But when you ask it to work with floats, it gets as confused as a penguin in a desert. It simply can't compute.

Modulo and floats go together like oil and water. The solution? Stick to integers when dealing with '%='.

So there you have it. Some common missteps while dancing with assignment operators and the quick moves to avoid them. Just remember, every great coder has tripped before. The key is to keep your chin up, learn from your stumbles, and soon you'll be waltzing with assignment operators like a seasoned pro.

Alright, amigos! It's time to put your newfound knowledge to the test. After all, becoming a master in the art of C assignment operators is not a walk in the park, it's a marathon run on a stony path with occasional dance-offs. So brace yourselves and let's get those brain cells pumping.

Exercise 1: The Shy Variable

Your task here is to write a C program that initializes an integer variable to 10. Then, using only assignment operators, make that variable as shy as a teenager at their first dance. I mean, reduce it to zero without directly assigning it to zero. You might want to remember the '/=' operator here. He's like the high school wallflower who can suddenly breakdance like a champ when the music starts playing.

Exercise 2: Sneaky Increment

The '+=' operator is like the mischievous friend who always pushes you into the spotlight when you least expect it. Create a program that initializes an integer to 0. Then, using a loop and our sneaky '+=' friend, increment that variable until it's equal to 100. Here's the catch: You can't use '+=' with anything greater than 1. It's a slow and steady race to the finish line!

Exercise 3: Modulo Madness

Remember the modulo operator? It's like the friend who always knows how much pizza is left over after a party. Create a program that counts from 1 to 100. But here's the twist: for every number that's divisible by 3, print "Fizz", and for every number divisible by 5, print "Buzz". If a number is divisible by both 3 and 5, print "FizzBuzz". For all other numbers, just print the number. This will help you get better acquainted with our friend '%='.

Exercise 4: Swapping Values

Create a program that swaps the values of two variables without using a third temporary variable. Remember, your only allies here are the assignment operators. This is like trying to switch places on the dance floor without stepping on anyone's toes.

Exercise 5: Converting Fahrenheit To Celsius

Let's play with the ' =' operator. Write a program that converts a temperature in Fahrenheit to Celsius. The formula to convert Fahrenheit to Celsius is (Fahrenheit - 32) * 5 / 9 . As a challenge, try doing the conversion in a single line using the '-=', ' =' and '/=' operators. It's like preparing a complicated dinner recipe using only a few simple steps.

Remember, practice makes perfect, especially when it comes to mastering C assignment operators. Don't be disheartened if you stumble, just dust yourself off and try again. Because as the saying goes, "The master has failed more times than the beginner has even tried". So, good luck, and happy coding!

References and Further Reading

So, you've reached the end of this riveting journey through the meadows of C assignment operators. It's been quite a ride, hasn't it? We've shared laughs, shed tears, and hopefully, we've learned a thing or two. But remember, the end of one journey marks the beginning of another. It's like eating at a buffet – you might be done with the pasta, but there's still the sushi to try! So, here are some materials to sink your teeth into for the next course of your coding feast.

1. The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie

This book, also known as 'K&R' after its authors, is the definitive guide to C programming. It's like the "Godfather" of programming books – deep, powerful, and a little intimidating at times. But hey, we all know that the best lessons come from challenging ourselves.

2. Expert C Programming by Peter van der Linden

Consider this book as the "Star Wars" to the "Godfather" of 'K&R'. It has a bit more adventure and a lot of real-world applications to keep you engaged. Not to mention some rather amusing footnotes.

3. C Programming Absolute Beginner's Guide by Greg Perry and Dean Miller

This one's for you if you're still feeling a bit wobbly on your C programming legs. Think of it as a warm hug from a friend who's been there and done that. It's simple, straightforward, and gently walks you through the concepts.

4. The Pragmatic Programmer by Andrew Hunt and David Thomas

Even though it's not about C specifically, this book is a must-read for any serious programmer. It's like a mentor who shares all their best tips and tricks for mastering the craft. It's filled with practical advice and real-life examples to help you on your programming journey.

This is a great online resource for interactive C tutorials. It's like your favorite video game, but it's actually helping you become a better programmer.

6. Cprogramming.com

This website has a vast collection of articles, tutorials, and quizzes on C programming. It's like an all-you-can-eat buffet for your hungry, coding mind.

Remember, every master was once a beginner, and every beginner can become a master. So, keep reading, keep practicing, and keep coding. And most importantly, don't forget to have fun while you're at it. After all, as Douglas Adams said, "I may not have gone where I intended to go, but I think I have ended up where I needed to be." Here's to ending up where you need to be in your coding journey!

As our immersive journey into C Assignment Operators culminates, we've unraveled the nuanced details of these powerful tools. From fundamental syntax to intricate applications, C Assignment Operators have showcased their indispensability in coding. Equipped with this newfound understanding, it's time for you to embark on your coding adventures, mastering the digital realm with the prowess of C Assignment Operators!

Which C assignment operator adds a value to a variable?

Please submit an answer to see if you're correct!

Continue Learning With These C Guides

  • C Syntax Explained: From Variables To Functions
  • C Programming Basics And Its Applications
  • Basic C Programming Examples For Beginners
  • C Data Types And Their Usage
  • C Variables And Their Usage

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

  • Enterprise Java
  • Web-based Java
  • Data & Java
  • Project Management
  • Visual Basic
  • Ruby / Rails
  • Java Mobile
  • Architecture & Design
  • Open Source
  • Web Services

Developer.com

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More .

Java Programming tutorials

Java provides many types of operators to perform a variety of calculations and functions, such as logical , arithmetic , relational , and others. With so many operators to choose from, it helps to group them based on the type of functionality they provide. This programming tutorial will focus on Java’s numerous a ssignment operators.

Before we begin, however, you may want to bookmark our other tutorials on Java operators, which include:

  • Arithmetic Operators
  • Comparison Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise and Shift Operators

Assignment Operators in Java

As the name conveys, assignment operators are used to assign values to a variable using the following syntax:

The left side operand of the assignment operator must be a variable, whereas the right side operand of the assignment operator may be a literal value or another variable. Moreover, the value or variable on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. Assignment operators have a right to left associativity in that the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side variable must be declared before assignment.

You can learn more about variables in our programming tutorial: Working with Java Variables .

Types of Assignment Operators in Java

Java assignment operators are classified into two types: simple and compound .

The Simple assignment operator is the equals ( = ) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left.

Compound operators are comprised of both an arithmetic, bitwise, or shift operator in addition to the equals ( = ) sign.

Equals Operator (=) Java Example

First, let’s learn to use the one-and-only simple assignment operator – the Equals ( = ) operator – with the help of a Java program. It includes two assignments: a literal value to num1 and the num1 variable to num2 , after which both are printed to the console to show that the values have been assigned to the numbers:

The += Operator Java Example

A compound of the + and = operators, the += adds the current value of the variable on the left to the value on the right before assigning the result to the operand on the left. Here is some sample code to demonstrate how to use the += operator in Java:

The -= Operator Java Example

Made up of the – and = operators, the -= first subtracts the variable’s value on the right from the current value of the variable on the left before assigning the result to the operand on the left. We can see it at work below in the following code example showing how to decrement in Java using the -= operator:

The *= Operator Java Example

This Java operator is comprised of the * and = operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. Here’s a program that shows the *= operator in action:

The /= Operator Java Example

A combination of the / and = operators, the /= Operator divides the current value of the variable on the left by the value on the right and then assigns the quotient to the operand on the left. Here is some example code showing how to use the  /= operator in Java:

%= Operator Java Example

The %= operator includes both the % and = operators. As seen in the program below, it divides the current value of the variable on the left by the value on the right and then assigns the remainder to the operand on the left:

Compound Bitwise and Shift Operators in Java

The Bitwise and Shift Operators that we just recently covered can also be utilized in compound form as seen in the list below:

  • &= – Compound bitwise Assignment operator.
  • ^= – Compound bitwise ^ assignment operator.
  • >>= – Compound right shift assignment operator.
  • >>>= – Compound right shift filled 0 assignment operator.
  • <<= – Compound left shift assignment operator.

The following program demonstrates the working of all the Compound Bitwise and Shift Operators :

Final Thoughts on Java Assignment Operators

This programming tutorial presented an overview of Java’s simple and compound assignment Operators. An essential building block to any programming language, developers would be unable to store any data in their programs without them. Though not quite as indispensable as the equals operator, compound operators are great time savers, allowing you to perform arithmetic and bitwise operations and assignment in a single line of code.

Read more Java programming tutorials and guides to software development .

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

What is the role of a project manager in software development, how to use optional in java, overview of the jad methodology, microsoft project tips and tricks, how to become a project manager in 2023, related stories, understanding types of thread synchronization errors in java, understanding memory consistency in java threads.

Developer.com
  • Modulo operator (%) in Python
  • Python Bitwise Operators
  • Python - Star or Asterisk operator ( * )
  • New '=' Operator in Python3.8 f-string
  • Format a Number Width in Python
  • Difference between != and is not operator in Python
  • Operator Overloading in Python
  • Python Object Comparison : "is" vs "=="
  • Python | a += b is not always a = a + b
  • Python Arithmetic Operators
  • Python Operators
  • Python | Operator.countOf
  • Assignment Operators in Python

    Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, bitwise computations. The value the operator operates on is known as Operand .

    Here, we will cover Assignment Operators in Python. So, Assignment Operators are used to assigning values to variables. 

    Now Let’s see each Assignment Operator one by one.

    1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand.

    2) Add and Assign: This operator is used to add the right side operand with the left side operand and then assigning the result to the left operand.

    Syntax: 

    3) Subtract and Assign: This operator is used to subtract the right operand from the left operand and then assigning the result to the left operand.

    Example –

     4) Multiply and Assign: This operator is used to multiply the right operand with the left operand and then assigning the result to the left operand.

     5) Divide and Assign: This operator is used to divide the left operand with the right operand and then assigning the result to the left operand.

     6) Modulus and Assign: This operator is used to take the modulus using the left and the right operands and then assigning the result to the left operand.

    7) Divide (floor) and Assign: This operator is used to divide the left operand with the right operand and then assigning the result(floor) to the left operand.

     8) Exponent and Assign: This operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.

    9) Bitwise AND and Assign: This operator is used to perform Bitwise AND on both operands and then assigning the result to the left operand.

    10) Bitwise OR and Assign: This operator is used to perform Bitwise OR on the operands and then assigning result to the left operand.

    11) Bitwise XOR and Assign:  This operator is used to perform Bitwise XOR on the operands and then assigning result to the left operand.

    12) Bitwise Right Shift and Assign: This operator is used to perform Bitwise right shift on the operands and then assigning result to the left operand.

     13) Bitwise Left Shift and Assign:  This operator is used to perform Bitwise left shift on the operands and then assigning result to the left operand.

    Please Login to comment...

    Similar reads.

    author

    • Python-Operators

    advertisewithusBannerImg

    Improve your Coding Skills with Practice

     alt=

    Specifications

    Browser compatibility.

    An assignment operator assigns a value to its left operand based on the value of its right operand.

    The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

    The basic assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x . The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

    Simple assignment operator is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example.

    Addition assignment

    The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.

    Subtraction assignment

    The subtraction assignment operator subtracts the value of the right operand from a variable and assigns the result to the variable. See the subtraction operator for more details.

    Multiplication assignment

    The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

    Division assignment

    The division assignment operator divides a variable by the value of the right operand and assigns the result to the variable. See the division operator for more details.

    Remainder assignment

    The remainder assignment operator divides a variable by the value of the right operand and assigns the remainder to the variable. See the remainder operator for more details.

    Exponentiation assignment

    The exponentiation assignment operator evaluates to the result of raising first operand to the power second operand. See the exponentiation operator for more details.

    Left shift assignment

    The left shift assignment operator moves the specified amount of bits to the left and assigns the result to the variable. See the left shift operator for more details.

    Right shift assignment

    The right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the right shift operator for more details.

    Unsigned right shift assignment

    The unsigned right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the unsigned right shift operator for more details.

    Bitwise AND assignment

    The bitwise AND assignment operator uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable. See the bitwise AND operator for more details.

    Bitwise XOR assignment

    The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable. See the bitwise XOR operator for more details.

    Bitwise OR assignment

    The bitwise OR assignment operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable. See the bitwise OR operator for more details.

    Left operand with another assignment operator

    In unusual situations, the assignment operator (e.g. x += y ) is not identical to the meaning expression (here x = x + y ). When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

    • Arithmetic operators

    Document Tags and Contributors

    • JavaScript basics
    • JavaScript first steps
    • JavaScript building blocks
    • Introducing JavaScript objects
    • Introduction
    • Grammar and types
    • Control flow and error handling
    • Loops and iteration
    • Expressions and operators
    • Numbers and dates
    • Text formatting
    • Regular expressions
    • Indexed collections
    • Keyed collections
    • Working with objects
    • Details of the object model
    • Using promises
    • Iterators and generators
    • Meta programming
    • JavaScript modules
    • Client-side web APIs
    • A re-introduction to JavaScript
    • JavaScript data structures
    • Equality comparisons and sameness
    • Inheritance and the prototype chain
    • Strict mode
    • JavaScript typed arrays
    • Memory Management
    • Concurrency model and Event Loop
    • References:
    • ArrayBuffer
    • AsyncFunction
    • Float32Array
    • Float64Array
    • GeneratorFunction
    • InternalError
    • Intl.Collator
    • Intl.DateTimeFormat
    • Intl.ListFormat
    • Intl.Locale
    • Intl.NumberFormat
    • Intl.PluralRules
    • Intl.RelativeTimeFormat
    • ReferenceError
    • SharedArrayBuffer
    • SyntaxError
    • Uint16Array
    • Uint32Array
    • Uint8ClampedArray
    • WebAssembly
    • decodeURI()
    • decodeURIComponent()
    • encodeURI()
    • encodeURIComponent()
    • parseFloat()
    • Array comprehensions
    • Bitwise operators
    • Comma operator
    • Comparison operators
    • Conditional (ternary) operator
    • Destructuring assignment
    • Expression closures
    • Generator comprehensions
    • Grouping operator
    • Legacy generator function expression
    • Logical operators
    • Object initializer
    • Operator precedence
    • (currently at stage 1) pipes the value of an expression into a function. This allows the creation of chained function calls in a readable manner. The result is syntactic sugar in which a function call with a single argument can be written like this:">Pipeline operator
    • Property accessors
    • Spread syntax
    • async function expression
    • class expression
    • delete operator
    • function expression
    • function* expression
    • in operator
    • new operator
    • void operator
    • Legacy generator function
    • async function
    • for await...of
    • for each...in
    • function declaration
    • import.meta
    • try...catch
    • Arrow functions
    • Default parameters
    • Method definitions
    • Rest parameters
    • The arguments object
    • constructor
    • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
    • InternalError: too much recursion
    • RangeError: argument is not a valid code point
    • RangeError: invalid array length
    • RangeError: invalid date
    • RangeError: precision is out of range
    • RangeError: radix must be an integer
    • RangeError: repeat count must be less than infinity
    • RangeError: repeat count must be non-negative
    • ReferenceError: "x" is not defined
    • ReferenceError: assignment to undeclared variable "x"
    • ReferenceError: can't access lexical declaration`X' before initialization
    • ReferenceError: deprecated caller or arguments usage
    • ReferenceError: invalid assignment left-hand side
    • ReferenceError: reference to undefined property "x"
    • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
    • SyntaxError: "use strict" not allowed in function with non-simple parameters
    • SyntaxError: "x" is a reserved identifier
    • SyntaxError: JSON.parse: bad parsing
    • SyntaxError: Malformed formal parameter
    • SyntaxError: Unexpected token
    • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
    • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
    • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
    • SyntaxError: for-in loop head declarations may not have initializers
    • SyntaxError: function statement requires a name
    • SyntaxError: identifier starts immediately after numeric literal
    • SyntaxError: illegal character
    • SyntaxError: invalid regular expression flag "x"
    • SyntaxError: missing ) after argument list
    • SyntaxError: missing ) after condition
    • SyntaxError: missing : after property id
    • SyntaxError: missing ; before statement
    • SyntaxError: missing = in const declaration
    • SyntaxError: missing ] after element list
    • SyntaxError: missing formal parameter
    • SyntaxError: missing name after . operator
    • SyntaxError: missing variable name
    • SyntaxError: missing } after function body
    • SyntaxError: missing } after property list
    • SyntaxError: redeclaration of formal parameter "x"
    • SyntaxError: return not in function
    • SyntaxError: test for equality (==) mistyped as assignment (=)?
    • SyntaxError: unterminated string literal
    • TypeError: "x" has no properties
    • TypeError: "x" is (not) "y"
    • TypeError: "x" is not a constructor
    • TypeError: "x" is not a function
    • TypeError: "x" is not a non-null object
    • TypeError: "x" is read-only
    • TypeError: 'x' is not iterable
    • TypeError: More arguments needed
    • TypeError: Reduce of empty array with no initial value
    • TypeError: can't access dead object
    • TypeError: can't access property "x" of "y"
    • TypeError: can't assign to property "x" on "y": not an object
    • TypeError: can't define property "x": "obj" is not extensible
    • TypeError: can't delete non-configurable array element
    • TypeError: can't redefine non-configurable property "x"
    • TypeError: cannot use 'in' operator to search for 'x' in 'y'
    • TypeError: cyclic object value
    • TypeError: invalid 'instanceof' operand 'x'
    • TypeError: invalid Array.prototype.sort argument
    • TypeError: invalid arguments
    • TypeError: invalid assignment to const "x"
    • TypeError: property "x" is non-configurable and can't be deleted
    • TypeError: setting getter-only property "x"
    • TypeError: variable "x" redeclares argument
    • URIError: malformed URI sequence
    • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
    • Warning: 08/09 is not a legal ECMA-262 octal constant
    • Warning: Date.prototype.toLocaleFormat is deprecated
    • Warning: JavaScript 1.6's for-each-in loops are deprecated
    • Warning: String.x is deprecated; use String.prototype.x instead
    • Warning: expression closures are deprecated
    • Warning: unreachable code after return statement
    • X.prototype.y called on incompatible type
    • JavaScript technologies overview
    • Lexical grammar
    • Enumerability and ownership of properties
    • Iteration protocols
    • Transitioning to strict mode
    • Template literals
    • Deprecated features
    • ECMAScript 2015 support in Mozilla
    • ECMAScript 5 support in Mozilla
    • Firefox JavaScript changelog
    • New in JavaScript 1.1
    • New in JavaScript 1.2
    • New in JavaScript 1.3
    • New in JavaScript 1.4
    • New in JavaScript 1.5
    • New in JavaScript 1.6
    • New in JavaScript 1.7
    • New in JavaScript 1.8
    • New in JavaScript 1.8.1
    • New in JavaScript 1.8.5
    • Documentation:
    • All pages index
    • Methods index
    • Properties index
    • Pages tagged "JavaScript"
    • JavaScript doc status
    • The MDN project

    Learn the best of web development

    Get the latest and greatest from MDN delivered straight to your inbox.

    Thanks! Please check your inbox to confirm your subscription.

    If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

    This browser is no longer supported.

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

    ?? and ??= operators - the null-coalescing operators

    • 9 contributors

    The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null ; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null. The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

    The left-hand operand of the ??= operator must be a variable, a property , or an indexer element.

    The type of the left-hand operand of the ?? and ??= operators can't be a non-nullable value type. In particular, you can use the null-coalescing operators with unconstrained type parameters:

    The null-coalescing operators are right-associative. That is, expressions of the form

    are evaluated as

    The ?? and ??= operators can be useful in the following scenarios:

    In expressions with the null-conditional operators ?. and ?[] , you can use the ?? operator to provide an alternative expression to evaluate in case the result of the expression with null-conditional operations is null :

    When you work with nullable value types and need to provide a value of an underlying value type, use the ?? operator to specify the value to provide in case a nullable type value is null :

    Use the Nullable<T>.GetValueOrDefault() method if the value to be used when a nullable type value is null should be the default value of the underlying value type.

    You can use a throw expression as the right-hand operand of the ?? operator to make the argument-checking code more concise:

    The preceding example also demonstrates how to use expression-bodied members to define a property.

    You can use the ??= operator to replace the code of the form

    with the following code:

    Operator overloadability

    The operators ?? and ??= can't be overloaded.

    C# language specification

    For more information about the ?? operator, see The null coalescing operator section of the C# language specification .

    For more information about the ??= operator, see the feature proposal note .

    • Null check can be simplified (IDE0029, IDE0030, and IDE0270)
    • C# operators and expressions
    • ?. and ?[] operators
    • ?: operator

    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

    We Love Servers.

    • WHY IOFLOOD?
    • BARE METAL CLOUD
    • DEDICATED SERVERS

    Understanding the Java += (Addition Assignment) Operator

    java_additional_assignment_operator_symbols

    Stumped by the ‘+=’ operator in Java? You’re not alone. Many developers find this operator a bit puzzling, but it’s actually a handy tool that can simplify your code and make your programming tasks easier.

    Think of the ‘+=’ operator in Java as a mathematical shortcut – a bridge that connects your variables and values in a more efficient way. It’s a powerful tool that can streamline your code, making it more readable and maintainable.

    In this guide, we’ll walk you through the process of understanding and using the ‘+=’ operator in Java , from the basics to more advanced techniques. We’ll cover everything from simple assignments and calculations to its use with strings and arrays, and even discuss alternative approaches.

    So, let’s dive in and start mastering the ‘+=’ operator in Java!

    TL;DR: What Does ‘+=’ Mean in Java?

    In Java, the ‘+=’ represents the additional assignment operator and is used to add the right operand to the left operand and assign the result back to the left operand, with the syntax, operandA += operandB . It’s a shorthand for a common operation that can make your code more concise and easier to read.

    Here’s a simple example:

    In this example, we declare an integer a and assign it a value of 5. Then, we use the ‘+=’ operator to add 3 to a and assign the result back to a . When we print out a , the output is 8.

    This is just a basic use of the ‘+=’ operator in Java, but there’s much more to learn about this operator and how it can simplify your code. Continue reading for more detailed information and advanced usage scenarios.

    Table of Contents

    The Basics of ‘+=’ in Java

    Advanced uses of ‘+=’ in java, exploring alternatives to ‘+=’ in java, troubleshooting java ‘+=’ operator issues, digging into java operators, applying ‘+=’ operator in larger java projects, wrapping up: additional assignment ‘+=’ operator.

    The ‘+=’ operator in Java is a compound assignment operator. It’s a shorthand that combines the addition and assignment operations into a single operation. This operator adds the right operand to the left operand and then assigns the result back to the left operand.

    Let’s look at a simple example:

    In this example, we declare an integer b and assign it a value of 10. Then, we use the ‘+=’ operator to add 5 to b and assign the result back to b . When we print out b , the output is 15.

    Advantages of Using ‘+=’

    One of the main advantages of using the ‘+=’ operator is that it can make your code more concise and easier to read. Instead of writing b = b + 5; , you can simply write b += 5; .

    Pitfalls to Avoid

    While the ‘+=’ operator can simplify your code, it’s important to be aware of potential pitfalls. For example, if you use the ‘+=’ operator with a null value, you’ll get a NullPointerException. It’s also important to remember that the ‘+=’ operator performs an implicit cast, which can lead to unexpected results if you’re not careful.

    Here’s an example:

    In this example, the ‘+=’ operator performs an implicit cast from int (the type of the right operand) to byte (the type of the left operand). The result is -116, which might not be what you expected.

    While the ‘+=’ operator is commonly used with numeric types, it can also be used with other types in Java, such as strings and arrays. This versatility can lead to more complex and interesting use cases.

    ‘+=’ with Strings

    In Java, the ‘+=’ operator can be used to concatenate strings. Here’s an example:

    In this example, we declare a string s and assign it a value of “Java”. Then, we use the ‘+=’ operator to append ” programming” to s . When we print out s , the output is “Java programming”.

    ‘+=’ with Arrays

    The ‘+=’ operator can also be used with arrays in Java. However, it’s important to note that this usage is not as straightforward as with numeric types or strings. Here’s an example:

    In this example, we declare an array and use a for loop to iterate through each element. We use the ‘+=’ operator to add 5 to each element in the array. When we print out the elements of the array, the output is 6, 7, 8.

    These advanced uses of the ‘+=’ operator can help you write more efficient and concise code in Java, especially when working with strings and arrays.

    While the ‘+=’ operator is a powerful tool in Java, there are other related operators that you can use depending on the specific needs of your code. Understanding these alternatives can give you more flexibility and control over your code.

    The ‘+’ Operator

    The ‘+’ operator in Java is the most basic form of addition. It adds the right operand to the left operand.

    In this example, we’re doing the same thing as c += 3; , but we’re writing it out in a longer form. The ‘+’ operator is straightforward and easy to understand, but it can make your code more verbose.

    The ‘++’ Operator

    The ‘++’ operator in Java is an increment operator. It increases the value of the variable by 1.

    In this example, we’re increasing the value of d by 1. The ‘++’ operator is a concise way to increment a variable, but it’s limited to increasing the value by 1.

    Decision-Making Considerations

    When deciding which operator to use, consider the needs of your code and the readability of your code. The ‘+=’ operator can make your code more concise, but it might be less clear to someone who isn’t familiar with this operator. The ‘+’ and ‘++’ operators are more explicit, but they can make your code more verbose.

    Understanding these alternatives to the ‘+=’ operator can help you write more efficient and readable code in Java.

    While the ‘+=’ operator in Java is a powerful tool, it’s not without its potential pitfalls. Understanding these common issues and how to address them can save you time and frustration.

    Dealing with Null Values

    One common issue is attempting to use the ‘+=’ operator with a null value. This will result in a NullPointerException.

    In this example, we attempt to use the ‘+=’ operator to append ” programming” to a null string. This results in a NullPointerException. To avoid this, always ensure that your variables are initialized before using them with the ‘+=’ operator.

    Implicit Casting

    Another common issue is the implicit casting that occurs when using the ‘+=’ operator. This can lead to unexpected results.

    In this example, the ‘+=’ operator performs an implicit cast from int (the type of the right operand) to byte (the type of the left operand), resulting in an unexpected value. To avoid this, be mindful of the types of your variables and the potential for implicit casting.

    Optimization Tips

    While the ‘+=’ operator can make your code more concise, it’s not always the most efficient choice. For example, if you’re performing a large number of additions, it might be more efficient to use a StringBuilder when working with strings, or to use a loop or a built-in method when working with arrays.

    Understanding these common issues and best practices can help you use the ‘+=’ operator more effectively in Java.

    Operators in Java are special symbols that perform specific operations on one, two, or three operands, and then return a result. They are the building blocks of any Java program, allowing us to perform calculations, manipulate bits, compare values, and more.

    The Role of Operators in Java

    Operators play a pivotal role in Java programming. They allow us to perform basic mathematical operations like addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). They also let us compare values and determine logic ( == , != , > , < , && , || ), manipulate bits ( <> , & , | ), and more.

    The Importance of ‘+=’ Operator

    Among these operators, ‘+=’ holds a special place due to its dual functionality. It’s a compound assignment operator that performs both addition and assignment in a single step. This not only makes our code more concise but also can lead to performance improvements in certain situations.

    In this example, we use the ‘+=’ operator to add 5 to x and assign the result back to x in a single step. This is more efficient than performing the addition and assignment in two separate steps.

    The ‘+=’ Operator in the Broader Context of Java

    The ‘+=’ operator is part of a family of compound assignment operators in Java, which also includes ‘-=’, ‘*=’, ‘/=’, and more. These operators all combine an arithmetic operation with an assignment, making our code more concise and potentially more efficient.

    Understanding the ‘+=’ operator and its role in Java programming is key to mastering Java and writing efficient, readable code.

    The ‘+=’ operator is not just for small programs or quick scripts. It can be a valuable tool in larger Java projects, where code efficiency and readability become critical.

    In large codebases, the ‘+=’ operator can help simplify complex calculations and assignments, making the code easier to understand and maintain. It can also reduce the chance of errors, as it reduces the need to repeat variable names.

    Related Topics to Explore

    The ‘+=’ operator often accompanies several related topics in typical use cases. Understanding these related concepts can provide a more holistic view of Java programming. These include other compound assignment operators like ‘-=’, ‘*=’, ‘/=’, and ‘%=’, as well as the broader topic of operator precedence in Java.

    Further Resources for Mastering Java Operators

    To further your understanding of the ‘+=’ operator and related concepts, here are some resources that offer more in-depth information:

    • Java Operator Tutorial: Getting Started – Discover Java’s bitwise operators for manipulating binary data.

    .equals Method in Java – Learn to compare the contents of objects for equality with the “.equals()” method in Java.

    Exploring ! Operator Usage – Understand how the “!” operator performs logical negation, flipping true to false and vice versa.

    Java Operators: Oracle Docs provides a comprehensive overview of all operators in Java, including the ‘+=’ operator.

    Java Compound Assignment Operators discusses the usage of compound assignment operators in Java.

    Java Operator Precedence explains operator precedence in Java, which determines how expressions involving the ‘+=’ operator are evaluated.

    In this comprehensive guide, we’ve demystified the ‘+=’ operator in Java, a handy tool that can simplify your code and streamline your programming tasks.

    We began with the basics, examining how the ‘+=’ operator functions as a mathematical shortcut in Java. We then delved into more advanced usage scenarios, such as using the ‘+=’ operator with strings and arrays. We also explored alternative approaches and related operators in Java, giving you a broader understanding of the Java operator landscape.

    Throughout our exploration, we tackled common issues and pitfalls associated with the ‘+=’ operator, such as dealing with null values and understanding implicit casting. We provided solutions and best practices to help you overcome these challenges.

    Here’s a quick comparison of the methods we’ve discussed:

    Whether you’re a beginner just starting out with Java or an experienced developer looking to brush up on your skills, we hope this guide has shed light on the ‘+=’ operator in Java and its usage.

    The ‘+=’ operator is a powerful tool in your Java toolkit, offering a combination of simplicity, efficiency, and versatility. Now, you’re well equipped to use it in your Java projects. Happy coding!

    About Author

    Gabriel Ramuglia

    Gabriel Ramuglia

    Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

    Related Posts

    Computer graphic illustrating npm ci vs npm install focusing on differences and use cases

    IMAGES

    1. Assignment Operators in C

      right operand assignment operator

    2. PPT

      right operand assignment operator

    3. What is an operand in mathematics and computing?

      right operand assignment operator

    4. PPT

      right operand assignment operator

    5. PPT

      right operand assignment operator

    6. Assignment operator in Python

      right operand assignment operator

    VIDEO

    1. C++ Operators

    2. Core

    3. 06_Ruby basics ( Assignment Operators)

    4. Operators in PHP Part

    5. Polish Notation (Postfix) Calculator

    6. C++ Assignment operator using quincy 2005

    COMMENTS

    1. Assignment operators

      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. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast. it is equivalent to E1 = T{E2}

    2. Assignment Operators in C

      1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...

    3. Assignment operators

      An assignment operator assigns a value to its left operand based on the value of its right operand.. Overview. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = y assigns the value of y to x.The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

    4. Expressions and operators

      An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...

    5. C Assignment Operators

      Code language:C++(cpp) The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand. Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the ...

    6. Expressions and operators

      The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x . There are also compound assignment operators that are shorthand for the operations listed in the following table:

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

    8. Python's Assignment Operator: Write Robust Assignments

      To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

    9. 4.6: Assignment Operator

      The expression to the right of the assignment operator contains some identifier names. The program would fetch the values stored in those variables; add them together and get a value of 44; then assign the 44 to the total_students variable. ... The left side operand of the assignment operator is a variable and right side operand of the ...

    10. Assignment operators

      An assignment operator assigns a value to its left operand based on the value of its right operand.. Overview. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = y assigns the value of y to x.The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

    11. Assignment Operators in C

      Assignment Operators in C - In C, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable or an expression. The value to be assigned forms the right hand operand, whereas the variable to be assigned should be the operan

    12. Assignment operators

      In this article. The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or implicitly convertible to it.

    13. Operator precedence

      Assignment operators are right-associative, so you can write: a = b = 5; // same as writing a = (b = 5); with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5 — the return value of b = 5, a.k.a. right operand of the ...

    14. Right shift assignment (>>=)

      The right shift assignment (>>=) operator performs right shift on the two operands and assigns the result to the left operand.

    15. Assignment Operator in C

      The assignment operator ( = ) is used to assign a value to the variable. Its general format is as follows: variable = right_side. The operand on the left side of the assignment operator must be a variable and operand on the right-hand side must be a constant, variable or expression. Here are some examples:

    16. Mastering The Art Of Assignment: Exploring C Assignment Operators

      Master the art of C Assignment Operators with our comprehensive guide. Get insights into syntax, tips, usage scenarios, and comparisons to optimize your programming performance. ... Adds the right operand to the left operand and assigns the result to the left operand.-= The subtractor. Subtracts the right operand from the left operand and ...

    17. Java Assignment Operators

      Assignment Operators in Java. As the name conveys, assignment operators are used to assign values to a variable using the following syntax: variable operator value; The left side operand of the assignment operator must be a variable, whereas the right side operand of the assignment operator may be a literal value or another variable.

    18. Assignment Operators in Python

      Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, bitwise computations. The value the operator operates on is known as Operand. Here, we will cover Assignment Operators in Python. So, Assignment Operators are used to assigning values to variables.

    19. Assignment operators

      The basic assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x. The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples. Name. Shorthand operator.

    20. ?? and ??= operators

      The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

    21. Understanding the Java += (Addition Assignment) Operator

      The '+=' operator in Java is a compound assignment operator. It's a shorthand that combines the addition and assignment operations into a single operation. This operator adds the right operand to the left operand and then assigns the result back to the left operand. Let's look at a simple example:

    22. Logical OR assignment (||=)

      Description. Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js.

    23. assignment operators Flashcards

      assignment operators. =. Click the card to flip 👆. Simple assignment operator, Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C. Click the card to flip 👆. 1 / 9.