CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • 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 - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • Decision Making in C
  • 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
  • Functions in C
  • C - Functions
  • C - Main Function
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • Arrays in C
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • 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 language, 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 the " = " 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 −

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C
+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Simple Assignment Operator (=)

The = operator is one of the most frequently used operators in C. As per the 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".

Run the code and check its output −

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 will produce the following result −

cppreference.com

Assignment operators.

(C11)
Miscellaneous
General
(C11)
(C99)

Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right.

Operator Operator name Example Description Equivalent of
= basic assignment a = b becomes equal to
+= addition assignment a += b becomes equal to the addition of and a = a + b
-= subtraction assignment a -= b becomes equal to the subtraction of from a = a - b
*= multiplication assignment a *= b becomes equal to the product of and a = a * b
/= division assignment a /= b becomes equal to the division of by a = a / b
%= modulo assignment a %= b becomes equal to the remainder of divided by a = a % b
&= bitwise AND assignment a &= b becomes equal to the bitwise AND of and a = a & b
|= bitwise OR assignment a |= b becomes equal to the bitwise OR of and a = a | b
^= bitwise XOR assignment a ^= b becomes equal to the bitwise XOR of and a = a ^ b
<<= bitwise left shift assignment a <<= b becomes equal to left shifted by a = a << b
>>= bitwise right shift assignment a >>= b becomes equal to right shifted by a = a >> b
Simple assignment Notes Compound assignment References See Also See also

[ edit ] Simple assignment

The simple assignment operator expressions have the form

lhs rhs
lhs - expression of any complete object type
rhs - expression of any type to lhs or with lhs

Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs .

Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as ( a = b ) = c are invalid).

rhs and lhs must satisfy one of the following:

  • both lhs and rhs have compatible struct or union type, or..
  • rhs must be implicitly convertible to lhs , which implies
  • both lhs and rhs have arithmetic types , in which case lhs may be volatile -qualified or atomic (since C11)
  • both lhs and rhs have pointer to compatible (ignoring qualifiers) types, or one of the pointers is a pointer to void, and the conversion would not add qualifiers to the pointed-to type. lhs may be volatile or restrict (since C99) -qualified or atomic (since C11) .
  • lhs is a (possibly qualified or atomic (since C11) ) pointer and rhs is a null pointer constant such as NULL or a nullptr_t value (since C23)
has type (possibly qualified or atomic(since C11)) _Bool and rhs is a pointer or a value(since C23) (since C99)
has type (possibly qualified or atomic) and rhs has type (since C23)

[ edit ] Notes

If rhs and lhs overlap in memory (e.g. they are members of the same union), the behavior is undefined unless the overlap is exact and the types are compatible .

Although arrays are not assignable, an array wrapped in a struct is assignable to another object of the same (or compatible) struct type.

The side effect of updating lhs is sequenced after the value computations, but not the side effects of lhs and rhs themselves and the evaluations of the operands are, as usual, unsequenced relative to each other (so the expressions such as i = ++ i ; are undefined)

Assignment strips extra range and precision from floating-point expressions (see FLT_EVAL_METHOD ).

In C++, assignment operators are lvalue expressions, not so in C.

[ edit ] Compound assignment

The compound assignment operator expressions have the form

lhs op rhs
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
lhs, rhs - expressions with (where lhs may be qualified or atomic), except when op is += or -=, which also accept pointer types with the same restrictions as + and -

The expression lhs @= rhs is exactly the same as lhs = lhs @ ( rhs ) , except that lhs is evaluated only once.

If lhs has type, the operation behaves as a single atomic read-modify-write operation with memory order .

For integer atomic types, the compound assignment @= is equivalent to:

addr = &lhs; T2 val = rhs; T1 old = *addr; T1 new; do { new = old @ val } while (! (addr, &old, new);
(since C11)

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.5.16 Assignment operators (p: 72-73)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.5.16 Assignment operators (p: 101-104)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.5.16 Assignment operators (p: 91-93)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.3.16 Assignment operators

[ edit ] See Also

Operator precedence

Common operators

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

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

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

!a
a && b
a || b

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

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

a(...)
a, b
(type) a
a ? b : c
sizeof


_Alignof
(since C11)

[ edit ] See also

for Assignment operators
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 19 August 2022, at 09:36.
  • 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:

OperatorOperation PerformedExampleEquivalent expression
Multiplication assignmentx *= yx = x * y
Division assignmentx /= yx = x / y
Remainder assignmentx %= yx = x % y
Addition assignmentx += yx = x + y
Subtraction assignmentx -= yx = x – y
Left-shift assignmentx <<= yx = x <<=y
Right-shift assignmentx >>=yx = x >>= y
Bitwise-AND assignmentx &= yx = x & y
Bitwise-exclusive-OR assignmentx ^= yx = x ^ y
Bitwise-inclusive-OR assignmentx |= yx = x | y
  • 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.

Print Cheatsheet

Mathmatical Symbols in C

C is able to perform basic mathematical operations on variables and values using the following symbols:

  • Addition: +
  • Subtraction: -
  • Division: /
  • Multiplication: *
  • Incrementing: ++
  • Decrementing: --

Assignment Operations in C

C can assign values to variables and perform basic mathematical operations using shorthand operators:

  • Assignment: =
  • Addition then assignment: +=
  • Subtraction then assignment: -=
  • Multiplication then assignment: *=
  • Division then assignment: /=
  • Modulo then assignment: %=

Comparing values in C

C can compare two values and/or variables against each other to return true or false. The operators are as follows:

  • Do both sides have the same value? ==
  • Do the two sides have different values? !=
  • Is the left side a lower value than the right side? <
  • Is the left side a lower or equal value to the right side? <=
  • Is the left side a greater value than the right side? >
  • Is the left side a greater or equal value to the right side? >=

Logical Operators in C

C can perform logical operations using the following operators:

  • and: && (Are both sides true?)
  • or: || (Is at least one side true?)
  • not: ! (True becomes false and false becomes true.)

This browser is no longer supported.

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

Assignment operators

  • 8 contributors

expression assignment-operator expression

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

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

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

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

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

Assignment operators table

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

Operator keywords

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

Operator Equivalent

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

Simple assignment

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

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

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

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

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

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

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

the assignment statement

can have one of the following effects:

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

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

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

Compound assignment

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

an arithmetic type

a pointer, if op is + or -

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

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

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

Result of built-in assignment operators

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

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

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

Was this page helpful?

Additional resources

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • C++ Tutorials
  • C++ Tutorial
  • C++ Hello World Program
  • C++ Comments
  • C++ Variables
  • Print datatype of variable
  • C++ If Else
  • Addition Operator
  • Subtraction Operator
  • Multiplication Operator
  • Division Operator
  • Modulus Operator
  • Increment Operator
  • Decrement Operator
  • Simple Assignment
  • Addition Assignment
  • Subtraction Assignment
  • Multiplication Assignment
  • Division Assignment
  • Remainder Assignment
  • Bitwise AND Assignment
  • ADVERTISEMENT
  • Bitwise OR Assignment
  • Bitwise XOR Assignment
  • Left Shift Assignment
  • Right Shift Assignment
  • Bitwise AND
  • Bitwise XOR
  • Bitwise Complement
  • Bitwise Left shift
  • Bitwise Right shift
  • Logical AND
  • Logical NOT
  • Not Equal to
  • Greater than
  • Greater than or Equal to
  • Less than or Equal to
  • Ternary Operator
  • Do-while loop
  • Infinite While loop
  • Infinite For loop
  • C++ Recursion
  • Create empty string
  • String length
  • String comparison
  • Get character at specific index
  • Get first character
  • Get last character
  • Find index of substring
  • Iterate over characters
  • Print unique characters
  • Check if strings are equal
  • Append string
  • Concatenate strings
  • String reverse
  • String replace
  • Swap strings
  • Convert string to uppercase
  • Convert string to lowercase
  • Append character at end of string
  • Append character to beginning of string
  • Insert character at specific index
  • Remove last character
  • Replace specific character
  • Convert string to integer
  • Convert integer to string
  • Convert string to char array
  • Convert char array to string
  • Initialize array
  • Array length
  • Print array
  • Loop through array
  • Basic array operations
  • Array of objects
  • Array of arrays
  • Convert array to vector
  • Sum of elements in array
  • Average of elements in array
  • Find largest number in array
  • Find smallest number in array
  • Sort integer array
  • Find string with least length in array
  • Create an empty vector
  • Create vector of specific size
  • Create vector with initial values
  • Copy a vector to another
  • Vector length or size
  • Vector of vectors
  • Vector print elements
  • Vector iterate using For loop
  • Vector iterate using While loop
  • Vector Foreach
  • Get reference to element at specific index
  • Check if vector is empty
  • Check if vectors are equal
  • Check if vector contains element
  • Update/Transform
  • Add element(s) to vector
  • Append element to vector
  • Append vector
  • Insert element at the beginning of vector
  • Remove first element from vector
  • Remove last element from vector
  • Remove element at specific index from vector
  • Remove duplicates from vector
  • Remove elements from vector based on condition
  • Resize vector
  • Swap elements of two vectors
  • Remove all elements from vector
  • Reverse a vector
  • Sort a vector
  • Conversions
  • Convert vector to map
  • Join vector elements to a string
  • Filter even numbers in vector
  • Filter odd numbers in vector
  • Get unique elements of a vector
  • Remove empty strings from vector
  • Sort integer vector in ascending order
  • Sort integer vector in descending order
  • Sort string vector based on length
  • Sort string vector lexicographically
  • Split vector into two equal halves
  • Declare tuple
  • Initialise tuple
  • Swap tuples
  • Unpack tuple elements into variables
  • Concatenate tuples
  • Constructor
  • Copy constructor
  • Virtual destructor
  • Friend class
  • Friend function
  • Inheritance
  • Multiple inheritance
  • Virtual inheritance
  • Function overloading
  • Operator overloading
  • Function overriding
  • C++ Try Catch
  • Math acos()
  • Math acosh()
  • Math asin()
  • Math asinh()
  • Math atan()
  • Math atan2()
  • Math atanh()
  • Math cbrt()
  • Math ceil()
  • Math copysign()
  • Math cosh()
  • Math exp2()
  • Math expm1()
  • Math fabs()
  • Math fdim()
  • Math floor()
  • Math fmax()
  • Math fmin()
  • Math fmod()
  • Math frexp()
  • Math hypot()
  • Math ilogb()
  • Math ldexp()
  • Math llrint()
  • Math llround()
  • Math log10()
  • Math log1p()
  • Math log2()
  • Math logb()
  • Math lrint()
  • Math lround()
  • Math modf()
  • Math nearbyint()
  • Math nextafter()
  • Math nexttoward()
  • Math remainder()
  • Math remquo()
  • Math rint()
  • Math round()
  • Math scalbln()
  • Math scalbn()
  • Math sinh()
  • Math sqrt()
  • Math tanh()
  • Math trunc()
  • Armstrong number
  • Average of three numbers
  • Convert decimal to binary
  • Factorial of a number
  • Factors of a number
  • Fibonacci series
  • Find largest of three numbers
  • Find quotient and remainder
  • HCF/GCD of two numbers
  • Hello World
  • LCM of two numbers
  • Maximum of three numbers
  • Multiply two numbers
  • Sum of two numbers
  • Sum of three numbers
  • Sum of natural numbers
  • Sum of digits in a number
  • Swap two numbers
  • Palindrome number
  • Palindrome string
  • Pattern printing
  • Power of a number
  • Prime number
  • Prime Numbers between two numbers
  • Print number entered by User
  • Reverse a Number
  • Read input from user
  • ❯ C++ Tutorial
  • ❯ C++ Operators
  • ❯ Assignment Operators
  • ❯ Multiplication Assignment

C++ Multiplication Assignment (*=) Operator

In this C++ tutorial, you shall learn about Multiplication Assignment operator, its syntax, and how to use this operator, with examples.

C++ Multiplication Assignment

In C++, Multiplication Assignment Operator is used to find the product of the value (right operand) and this variable (left operand) and assign the result back to this variable (left operand).

The syntax to find the product of a value 2 with variable x and assign the result to x using Multiplication Assignment Operator is

In the following example, we take a variable x with an initial value of 5 , multiply it with a value of 2 and assign the result back to x , using Multiplication Assignment Operator.

In this C++ Tutorial , we learned about Multiplication Assignment Operator in C++, with examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

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

Left Shift and Right Shift Operators in C/C++

In C/C++, left shift (<<) and right shift (>>) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators.

Left Shift (<<) Operators

The left shift(<<) is a binary operator that takes two numbers, left shifts the bits of the first operand, and the second operand decides the number of places to shift. In other words, left-shifting an integer “ a ” with an integer “ b ” denoted as ‘ (a<<b)’ is equivalent to multiplying a with 2^b (2 raised to power b).  

  • a is the integer value to be shifted.
  • b specifies how many positions to shift the bits.

Example: Let’s take a=5 ; which is 101 in Binary Form. Now, if “ a is left-shifted by 2 ” i.e a=a<<2 then a will become a=a*(2^2) . Thus, a=5*(2^2)=20 which can be written as 10100.

Left-Shift-in-c-cpp

Example of Left Shift Operator

Applications of left shift operator.

  • Multiplication by Powers of Two : Left shifting a number by n positions is equivalent to multiplying it by 2^n and is much faster than normal multiplication
  • Efficient Calculations : Used in performance-critical applications where arithmetic operations need to be fast.
  • Bit Manipulation : Common in low-level programming, such as embedded systems and hardware interfacing.

Right Shift(>>) Operators

Right Shift(>>) is a binary operator that takes two numbers, right shifts the bits of the first operand, and the second operand decides the number of places to shift. In other words, right-shifting an integer “ a ” with an integer “ b ” denoted as ‘ (a>>b) ‘ is equivalent to dividing a with 2^b. 

Example: let’s take a=5 ; which is 101 in Binary Form. Now, if “ a is right-shifted by 2 ” i.e a=a>>2 then a will become a=a/(2^2) . Thus, a=a/(2^2)=1 which can be written as 01 .

right-Shift-in-c-cpp

Example of Right Shift Operator

Applications of right shift operators.

  • Division by Powers of Two : Right shifting a number by n positions is equivalent to dividing it by 2^n and it is very fast.
  • Efficient Calculations : Used in performance-critical applications for fast division operations.
  • Bit Manipulation : Useful in extracting specific bits from data, common in data compression and cryptography.

Important Points of Shift Operators

1. The left-shift and right-shift operators should not be used for negative numbers. The result of is undefined behavior if any of the operands is a negative number. For example, results of both 1 >> -1 and 1 << -1 is undefined.

2. If the number is shifted more than the size of the integer, the behavior is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits. For bit shift of larger values 1ULL<<62   ULL is used for Unsigned Long Long which is defined using 64 bits that can store large values.

3. The left-shift by 1 and right-shift by 1 are equivalent to the product of the first term and 2 to the power given element(1<<3 = 1*pow(2,3)) and division of the first term and second term raised to power 2 (1>>3 = 1/pow(2,3)) respectively. 

Must Read: Bitwise Operators in C/C++

author

Please Login to comment...

Similar reads.

  • C++ Bit Manipulation
  • cpp-operator
  • How to Strikethrough on Discord
  • Discord Launches End-To-End Encryption For Audio & Video Chats
  • iPadOS 18 is Now Available: Complete Features and How to Install
  • Microsoft’s Latest 365 Copilot Updates: Enhanced AI Tools for Excel, PowerPoint, and Teams
  • 10 Best PrimeWire Alternatives (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Multiplication Assignment operator doesn't honor mathematical precedence

For example:

The first one I would have hoped would have worked correctly, and the compiler would have done the * first, but it didn’t. This is expected, because the * is on the left side to the assignment operator. Is there any way I can create another operator that operates like the ++ and – operators, kinda like this…

Operation and =* that would have the * on the right hand side, thus being a clear indicator that the * before the assignment operator is reached. I am just not sure how to break the rhs variable into pieces BEFORE it is evaluated.

Any ideas would be helpful.

Josh Noe's user avatar

  • I am pretty sure I can do it in .NET Assemby, but that will just get overwritten each time I recompile. –  Bugs Bunny Commented Dec 14, 2018 at 1:15
  • interesting question, on the docs it is stated the operator has higher precedence than the next section and lower precedence than the previous section (right-to-left). which means the addition will be done before the multiplication followed by the assignment - i = i * (15 + 12) . –  Bagus Tesa Commented Dec 14, 2018 at 1:26
  • Yes, but the right hand side is evaluated with correct rules of math operator precedence, then that result is multiplied by the value of the left and side and then assigned to the value, which is not correct. Multiplication takes higher precedence than addition. It’s a flaw, but only kind of a flaw. If they created behavior like =* then it would make a lot more sense. Kind of like the difference between ++variable and variable++ (aka early increment or late increment). –  Bugs Bunny Commented Dec 14, 2018 at 1:31
  • You are making an incorrect application of operator precedence: the opreator * is applied before the operator + in an expression, but the operator = and the operator *= are applied after the basic math operators + , - , * , / , hence the rhs is evaluated, then *= uses that. That is the definition in C# - operator evaluation is not a textual substitution (like a C pre-processor macro). Note that operator *= and operator * are not the same operator. –  NetMage Commented Dec 14, 2018 at 21:43
  • If *= had higher precedence, then the expression is (value *= 15) + 12; so what do you think the +12 would mean? –  NetMage Commented Dec 14, 2018 at 21:45

2 Answers 2

Your code doesn't make sense if you're hoping to change the precendence of the *= operator.

If I started with this (ignoring the fact that it's not valid C#):

... and then had this code:

... the call to =* would set lhs as 10 , but it would have to set rhs as the result of 15 + 12 .

And that would simply be the same behaviour of the built-in *= operator.

Enigmativity's user avatar

  • It’s pseudo code, and I wrote in it an email to Jon Skeet, not studio. I think you might understand what I want to do, but only maybe. I tested it in studio but wanted to express the issue more than copy my code from studio. –  Bugs Bunny Commented Dec 14, 2018 at 1:38
  • 1 @BugsBunny - Please show real code whenever possible. Expressing ideas with pseudo code is often misleading. –  Enigmativity Commented Dec 14, 2018 at 1:39
  • While completely correct, this might be better as a comment? :) –  Josh Noe Commented Dec 14, 2018 at 1:52
  • 1 @Enigmativity Because this doesn't answer the question. It only comments on a mistake made in the question. I could be misunderstanding. –  Josh Noe Commented Dec 14, 2018 at 14:39
  • 1 @JoshNoe - I was trying to illustrate that to pass a single value (i.e. Int32 rhs ) that the compiler must evaluate before calling the overload. There's no way for the compiler to get around this. You'd have to modify the compiler to get this functionality to work the way that the OP requested it. –  Enigmativity Commented Dec 14, 2018 at 22:17

Edit : Based on further comments by OP in the comment section of question, the operator was probably created to make it easier to write the aggregate operations : sum = sum + value , and so does not follow the normal mathematical rules, it is probably more useful then what you propose.

C# you cannot create new operator. The existing operators are built into the language, so to add any new one's at a minimum you would also want to implement some parts in compiler to parse them.

C# does allow operator overloading, but then it leads to defining your own integers and I don't think that is a happy road to go down.

There are languages other then C# which do allow this (notably functional languages where operators are just normal methods).

From C# language specifications

Certain operators can be overloaded. Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type (Operator overloading).

peeyush singh's user avatar

  • I can do it in .NET Assembly I am sure, but fix would be overwritten each compile. This is a perfect reason why all .NET Framework class should be labeled partial. LOL –  Bugs Bunny Commented Dec 14, 2018 at 1:35
  • That's the reason I mentioned that it would involve rewrite of some parts of compiler –  peeyush singh Commented Dec 14, 2018 at 1:37
  • Of course they can. I want to create a NEW operator that evaluates correctly with the rules of math operator precedence, not overload an existing one. –  Bugs Bunny Commented Dec 14, 2018 at 1:39
  • Agreed, and I can do that, but was hoping there was an easier way that one of you could think of. –  Bugs Bunny Commented Dec 14, 2018 at 1:40
  • Maybe I can create a post compile event that adds then assembly into the IL. That’s all I can think. –  Bugs Bunny Commented Dec 14, 2018 at 1:52

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Detecting errors in AI-generated code
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Uppercase, lowercase – "in any case"?
  • Are 8086 family microprocessors accumulator based?
  • Using of physical FPGA for PCB prototyping
  • If given 3 random real numbers between 0-100, what is the probability that the median is closest in value to 50?
  • Cheapest / Most efficient way for a human Wizard to not age?
  • Simple OP_EQUAL script (Script evaluated without error but finished with a false/empty top stack element)
  • How uncommon/problematic is a passport whose validity period (period between issue and expiry) is a non-whole number of years?
  • Where does the argument included below to "Prove the fundamental group of a Topological Group is abelian" fail for non-group topological spaces?
  • Returning to the US for 2 weeks after a short stay around 6 months prior with an ESTA but a poor entry interview - worried about visiting again
  • What does "(be) able to look sad" mean?
  • “…[it] became a ______ for me.” Why is "gift" the right answer?
  • How much would you trust a pre-sales inspection from a "captured" mechanic?
  • Why is angular momentum in a 2-body system conserved if the points about which we take them are moving?
  • Why Doesn't the cooling system on a rocket engine burn the fuel?
  • Trinitarian Christianity says Jesus was fully God and Fully man. Did Jesus (the man) know this to be the case?
  • SF story set in an isolated (extragalactic) star system
  • A novella (?) about "experts" in the theory of time travel and their "Socratic" mentor
  • Superuser and Sudo not working on Debian 12
  • Play the Final Fantasy Prelude
  • Enter a personal identification number
  • Terrible face recognition skills: how to improve
  • Why are Jesus and Satan both referred to as the morning star?
  • Linux wait command returning for finished jobs
  • Why is it surprising that the CMB is so homogeneous?

multiplying assignment operator c

COMMENTS

  1. Assignment Operators in C

    Assigns values from right side operands to left side operand. C = A + B will assign the value of A + B to C. +=. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A. -=. Subtract AND assignment operator.

  2. C Operator Precedence

    They are derived from the grammar. In C++, the conditional operator has the same precedence as assignment operators, and prefix ++ and -- and assignment operators don't have the restrictions about their operands. Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always ...

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

  4. Assignment operators

    Correct behavior. CWG 1527. C++11. for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) (T is the type of E1), this introduced a C-style cast.

  5. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs. Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

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

  7. Operators in C

    5. Assignment Operators in C. Assignment operators are used to assign value to a variable. The left side operand of the assignment operator is a variable and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type as the variable on the left side otherwise the compiler will raise ...

  8. Assignment Operators in Programming

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

  9. C Assignment Operators

    The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators: | =. In assignment, the type of the right-hand value is converted to the type of the left-hand value, and the value is stored in the left operand after the assignment has taken place.

  10. C Compound Assignment

    The compound-assignment operators combine the simple-assignment operator with another binary operator. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. For example, a compound-assignment expression such as. expression1 += expression2. can be understood as.

  11. c

    (Note that this sequencing freedom is specific to C language, in which the result of an assignment in an rvalue. In C++ assignment evaluates to an lvalue, which requires "chained" assignments to be sequenced.) ... The operator precedence of the = operator guarantees that this is executed right-to-left. In other words, it guarantees that sample2 ...

  12. Learn C: Operators Cheatsheet

    C can assign values to variables and perform basic mathematical operations using shorthand operators: Assignment: = ... Multiplication then assignment: *= Division then assignment: /= Modulo then assignment: %= Comparing values in C. C can compare two values and/or variables against each other to return true or false. The operators are as follows:

  13. Assignment operators

    Assignment operators table. Expand table. Operator. Meaning. =. Store the value of the second operand in the object specified by the first operand (simple assignment). *=. Multiply the value of the first operand by the value of the second operand; store the result in the object specified by the first operand. /=.

  14. C++ Multiplication Assignment (*=) Operator

    In C++, Multiplication Assignment Operator is used to find the product of the value (right operand) and this variable (left operand) and assign the result back to this variable (left operand). The syntax to find the product of a value 2 with variable x and assign the result to x using Multiplication Assignment Operator is. x *= 2.

  15. Operator Precedence and Associativity in C

    Pre-requisite:Bitwise Operators in C/ C++Bitwise Operators in Java The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1's become 0's and vice versa. The operator for the bitwise complement is ~ (Tilde). Example: Input

  16. Assignment Operators In C++

    In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another value. Syntax. variable *= value; This above expression is equivalent to the expression: variable = variable * value; Example. C++. #include <iostream>. using namespace std;

  17. Arithmetic Operators in C

    C provides 5 Binary Arithmetic Operators for performing arithmetic functions which are as follows: Add two operands. Subtract the second operand from the first operand. Multiply two operands. Divide the first operand by the second operand. Calculate the remainder when the first operand is divided by the second operand.

  18. operators

    In C++11 terminology, you can't have two unsequenced modifications of the same scalar or a modification and a value computation using the same scalar, otherwise you have undefined behaviour. x = x * x++;

  19. Left Shift and Right Shift Operators in C/C++

    The left shift (<<) is a binary operator that takes two numbers, left shifts the bits of the first operand, and the second operand decides the number of places to shift. In other words, left-shifting an integer "a" with an integer "b" denoted as '(a<<b)' is equivalent to multiplying a with 2^b (2 raised to power b). Syntax.

  20. c#

    You are making an incorrect application of operator precedence: the opreator * is applied before the operator + in an expression, but the operator = and the operator *= are applied after the basic math operators +,-,*,/, hence the rhs is evaluated, then *= uses that. That is the definition in C# - operator evaluation is not a textual substitution (like a C pre-processor macro).