This browser is no longer supported.

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

C Compound Assignment

  • 6 contributors

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

expression1 = expression1 + expression2

However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation.

The operands of a compound-assignment operator must be of integral or floating type. Each compound-assignment operator performs the conversions that the corresponding binary operator performs and restricts the types of its operands accordingly. The addition-assignment ( += ) and subtraction-assignment ( -= ) operators can also have a left operand of pointer type, in which case the right-hand operand must be of integral type. The result of a compound-assignment operation has the value and type of the left operand.

In this example, a bitwise-inclusive-AND operation is performed on n and MASK , and the result is assigned to n . The manifest constant MASK is defined with a #define preprocessor directive.

C Assignment Operators

Was this page helpful?

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

Submit and view feedback for

Additional resources

CsTutorialPoint - Computer Science Tutorials For Beginners

Assignment Operators In C [ Full Information With Examples ]

Assignment Operators In C

Assignment Operators In C

Assignment operators is a binary operator which is used to assign values in a variable , with its right and left sides being a one-one operand. The operand on the left side is variable in which the value is assigned and the right side operands can contain any of the constant, variable, and expression.

The Assignment operator is a lower priority operator. its priority has much lower than the rest of the other operators. Its priority is more than just the comma operator. The priority of all other operators is more than the assignment operator.

We can assign the same value to multiple variables simultaneously by the assignment operator.

x = y = z = 100

Here x, y, and z are initialized to 100.

In C language, the assignment operator can be divided into two categories.

  • Simple assignment operator
  • Compound assignment operators

1. Simple Assignment Operator In C

This operator is used to assign left-side values ​​to the right-side operands, simple assignment operators are represented by (=).

2. Compound Assignment Operators In C

Compound Assignment Operators use the old value of a variable to calculate its new value and reassign the value obtained from the calculation to the same variable.

Examples of compound assignment operators are: (Example: + =, – =, * =, / =,% =, & =, ^ =)

Look at these two statements:

Here in this example, adding 5 to the x variable in the second statement is again being assigned to the x variable.

Compound Assignment Operators provide us with the C language to perform such operation even more effecient and in less time.

Syntax of Compound Assignment Operators

Here op can be any arithmetic operators (+, -, *, /,%).

The above statement is equivalent to the following depending on the function:

Let us now know about some important compound assignment operators one by one.

“+ =” -: This operator adds the right operand to the left operand and assigns the output to the left operand.

“- =” -: This operator subtracts the right operand from the left operand and returns the result to the left operand.

“* =” -: This operator multiplies the right operand with the left operand and assigns the result to the left operand.

“/ =” -: This operator splits the left operand with the right operand and assigns the result to the left operand.

“% =” -: This operator takes the modulus using two operands and assigns the result to the left operand.

There are many other assignment operators such as left shift and (<< =) operator, right shift and operator (>> =), bitwise and assignment operator (& =), bitwise OR assignment operator (^ =)

List of Assignment Operators In C

=sum = 101;101 is assigned to variable sum
+=sum += 101; This is same as sum = sum + 101
-=sum -= 101; This is same as sum = sum – 101
*=sum *= 101; This is same as sum = sum * 101
/=sum /= 101; This is same as sum = sum/101
%=sum %= 101; This is same as sum = sum % 101
&=sum&=101; This is same as sum = sum & 101
^=sum ^= 101; This is same as sum = sum ^ 101

Read More -:

  • What is Operators In C
  • Relational Operators In C
  • Logical Operators In C
  • Bitwise Operators In C
  • Arithmetic Operators In C
  • Conditional Operator in C
  • Download C Language Notes Pdf
  • C Language Tutorial For Beginners
  • C Programming Examples With Output
  • 250+ C Programs for Practice PDF Free Download

Friends, I hope you have found the answer of your question and you will not have to search about the Assignment operators in C Language 

However, if you want any information related to this post or related to programming language, computer science, then comment below I will clear your all doubts.

If you want a complete tutorial of C language, then see here  C Language Tutorial . Here you will get all the topics of C Programming Tutorial step by step.

Friends, if you liked this post, then definitely share this post with your friends so that they can get information about the Assignment operators in C Language 

To get the information related to Programming Language, Coding, C, C ++, subscribe to our website newsletter. So that you will get information about our upcoming new posts soon.

' src=

Jeetu Sahu is A Web Developer | Computer Engineer | Passionate about Coding, Competitive Programming, and Blogging

Leave a Reply Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

Codeforwin

Assignment and shorthand assignment operator in C

Quick links.

  • Shorthand assignment

Assignment operator is used to assign value to a variable (memory location). There is a single assignment operator = in C. It evaluates expression on right side of = symbol and assigns evaluated value to left side the variable.

For example consider the below assignment table.

OperationDescription
Assigns 10 to variable
Evaluates expression and assign result to
Evaluates and assign result to
Error, you cannot re-assign a value to a constant
Error, you cannot re-assign a value to a constant

The RHS of assignment operator must be a constant, expression or variable. Whereas LHS must be a variable (valid memory location).

Shorthand assignment operator

C supports a short variant of assignment operator called compound assignment or shorthand assignment. Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator.

For example, consider following C statements.

The above expression a = a + 2 is equivalent to a += 2 .

Similarly, there are many shorthand assignment operators. Below is a list of shorthand assignment operators in C.

Shorthand assignment operatorExampleMeaning

compound assignment operators in c with example

  • Introduction to C
  • Download MinGW GCC C Compiler
  • Configure MinGW GCC C Compiler
  • The First C Program
  • Data Types in C
  • Variables, Keywords, Constants
  • If Statement
  • If Else Statement
  • Else If Statement
  • Nested If Statement
  • Nested If Else Statement
  • Do-While Loop
  • Break Statement
  • Switch Statement
  • Continue Statement
  • Goto Statement
  • Arithmetic Operator in C
  • Increment Operator in C
  • Decrement Operator in C
  • Compound Assignment Operator
  • Relational Operator in C
  • Logical Operator in C
  • Conditional Operator in C
  • 2D array in C
  • Functions with arguments
  • Function Return Types
  • Function Call by Value
  • Function Call by Reference
  • Recursion in C
  • Reading String from console
  • C strchr() function
  • C strlen() function
  • C strupr() function
  • C strlwr() function
  • C strcat() function
  • C strncat() function
  • C strcpy() function
  • C strncpy() function
  • C strcmp() function
  • C strncmp() function
  • Structure with array element
  • Array of structures
  • Formatted Console I/O functions
  • scanf() and printf() function
  • sscanf() and sprintf() function
  • Unformatted Console I/O functions
  • getch(), getche(), getchar(), gets()
  • putch(), putchar(), puts()
  • Reading a File
  • Writing a File
  • Append to a File
  • Modify a File

Advertisement

+= operator

  • Add operation.
  • Assignment of the result of add operation.
  • Statement i+=2 is equal to i=i+2 , hence 2 will be added to the value of i, which gives us 4.
  • Finally, the result of addition, 4 is assigned back to i, updating its original value from 2 to 4.

Example with += operator

-= operator.

  • Subtraction operation.
  • Assignment of the result of subtract operation.
  • Statement i-=2 is equal to i=i-2 , hence 2 will be subtracted from the value of i, which gives us 0.
  • Finally, the result of subtraction i.e. 0 is assigned back to i, updating its value to 0.

Example with -= operator

*= operator.

  • Multiplication operation.
  • Assignment of the result of multiplication operation.
  • Statement i*=2 is equal to i=i*2 , hence 2 will be multiplied with the value of i, which gives us 4.
  • Finally, the result of multiplication, 4 is assigned back to i, updating its value to 4.

Example with *= operator

/= operator.

  • Division operation.
  • Assignment of the result of division operation.
  • Statement i/=2 is equal to i=i/2 , hence 4 will be divided by the value of i, which gives us 2.
  • Finally, the result of division i.e. 2 is assigned back to i, updating its value from 4 to 2.

Example with /= operator

Please share this article -.

Facebook

Please Subscribe

Decodejava Facebook Page

Notifications

Please check our latest addition C#, PYTHON and DJANGO

Find Study Materials for

  • Explanations
  • Business Studies
  • Combined Science
  • Computer Science
  • Engineering
  • English literature
  • Environmental Science
  • Human Geography
  • Macroeconomics
  • Microeconomics
  • Social Studies
  • Browse all subjects
  • Textbook Solutions
  • Read our Magazine

Create Study Materials

  • Flashcards Create and find the best flashcards.
  • Notes Create notes faster than ever before.
  • Study Sets Everything you need for your studies in one place.
  • Study Plans Stop procrastinating with our smart planner features.
  • Assignment Operator in C

In the realm of computer programming , specifically in the C programming language, understanding and utilising assignment operators effectively is essential for developing efficient and well-organised code. The assignment operator in C plays a fundamental role in assigning values to variables, and this introductory piece will elaborate on its definition, usage and importance. Gain insights on different types of assignment operators, such as compound assignment operators and the assignment operator for strings in C. As you delve deeper, practical examples of the assignment operator in C will be provided, enabling you to gain a firm grasp on the concept and apply this knowledge for successful programming endeavours.

Assignment Operator in C

Create learning materials about Assignment Operator in C with our free learning app!

  • Instand access to millions of learning materials
  • Flashcards, notes, mock-exams and more
  • Everything you need to ace your exams
  • Algorithms in Computer Science
  • Computer Network
  • Computer Organisation and Architecture
  • Computer Programming
  • 2d Array in C
  • AND Operator in C
  • Access Modifiers
  • Actor Model
  • Algorithm in C
  • Array as function argument in c
  • Automatically Creating Arrays in Python
  • Bitwise Operators in C
  • C Arithmetic Operations
  • C Array of Structures
  • C Functions
  • C Math Functions
  • C Memory Address
  • C Plus Plus
  • C Program to Find Roots of Quadratic Equation
  • C Programming Language
  • Change Data Type in Python
  • Classes in Python
  • Comments in C
  • Common Errors in C Programming
  • Compound Statement in C
  • Concurrency Vs Parallelism
  • Concurrent Programming
  • Conditional Statement
  • Critical Section
  • Data Types in Programming
  • Declarative Programming
  • Decorator Pattern
  • Distributed Programming
  • Do While Loop in C
  • Dynamic allocation of array in c
  • Encapsulation programming
  • Event Driven Programming
  • Exception Handling
  • Executable File
  • Factory Pattern
  • For Loop in C
  • Formatted Output in C
  • Functions in Python
  • How to return multiple values from a function in C
  • Identity Operator in Python
  • Imperative programming
  • Increment and Decrement Operators in C
  • Inheritance in Oops
  • Insertion Sort Python
  • Instantiation
  • Integrated Development Environments
  • Integration in C
  • Interpreter Informatics
  • Java Abstraction
  • Java Annotations
  • Java Arithmetic Operators
  • Java Arraylist
  • Java Arrays
  • Java Assignment Operators
  • Java Bitwise Operators
  • Java Classes And Objects
  • Java Collections Framework
  • Java Constructors
  • Java Data Types
  • Java Do While Loop
  • Java Enhanced For Loop
  • Java Expection Handling
  • Java File Class
  • Java File Handling
  • Java Finally
  • Java For Loop
  • Java Function
  • Java Generics
  • Java IO Package
  • Java If Else Statements
  • Java If Statements
  • Java Inheritance
  • Java Interfaces
  • Java List Interface
  • Java Logical Operators
  • Java Map Interface
  • Java Method Overloading
  • Java Method Overriding
  • Java Multidimensional Arrays
  • Java Multiple Catch Blocks
  • Java Nested If
  • Java Nested Try
  • Java Non Primitive Data Types
  • Java Operators
  • Java Polymorphism
  • Java Primitive Data Types
  • Java Queue Interface
  • Java Recursion
  • Java Reflection
  • Java Relational Operators
  • Java Set Interface
  • Java Single Dimensional Arrays
  • Java Statements
  • Java Static Keywords
  • Java Switch Statement
  • Java Syntax
  • Java This Keyword
  • Java Try Catch
  • Java Type Casting
  • Java Virtual Machine
  • Java While Loop
  • Javascript Anonymous Functions
  • Javascript Arithmetic Operators
  • Javascript Array Methods
  • Javascript Array Sort
  • Javascript Arrays
  • Javascript Arrow Functions
  • Javascript Assignment Operators
  • Javascript Async
  • Javascript Asynchronous Programming
  • Javascript Await
  • Javascript Bitwise Operators
  • Javascript Callback
  • Javascript Callback Functions
  • Javascript Changing Elements
  • Javascript Classes
  • Javascript Closures
  • Javascript Comparison Operators
  • Javascript DOM Events
  • Javascript DOM Manipulation
  • Javascript Data Types
  • Javascript Do While Loop
  • Javascript Document Object
  • Javascript Event Loop
  • Javascript For In Loop
  • Javascript For Loop
  • Javascript For Of Loop
  • Javascript Function
  • Javascript Function Expressions
  • Javascript Hoisting
  • Javascript If Else Statement
  • Javascript If Statement
  • Javascript Immediately Invoked Function Expressions
  • Javascript Inheritance
  • Javascript Interating Arrays
  • Javascript Logical Operators
  • Javascript Loops
  • Javascript Multidimensional Arrays
  • Javascript Object Creation
  • Javascript Object Prototypes
  • Javascript Objects
  • Javascript Operators
  • Javascript Primitive Data Types
  • Javascript Promises
  • Javascript Reference Data Types
  • Javascript Scopes
  • Javascript Selecting Elements
  • Javascript Spread And Rest
  • Javascript Statements
  • Javascript Strict Mode
  • Javascript Switch Statement
  • Javascript Syntax
  • Javascript Ternary Operator
  • Javascript This Keyword
  • Javascript Type Conversion
  • Javascript While Loop
  • Linear Equations in C
  • Log Plot Python
  • Logical Error
  • Logical Operators in C
  • Loop in programming
  • Matrix Operations in C
  • Membership Operator in Python
  • Model View Controller
  • Nested Loops in C
  • Nested if in C
  • Numerical Methods in C
  • OR Operator in C
  • Object orientated programming
  • Observer Pattern
  • One Dimensional Arrays in C
  • Oops concepts
  • Operators in Python
  • Parameter Passing
  • Pascal Programming Language
  • Plot in Python
  • Plotting In Python
  • Pointer Array C
  • Pointers and Arrays
  • Pointers in C
  • Polymorphism programming
  • Procedural Programming
  • Programming Control Structures
  • Programming Language PHP
  • Programming Languages
  • Programming Paradigms
  • Programming Tools
  • Python Arithmetic Operators
  • Python Array Operations
  • Python Arrays
  • Python Assignment Operator
  • Python Bar Chart
  • Python Bitwise Operators
  • Python Bubble Sort
  • Python Comparison Operators
  • Python Data Types
  • Python Indexing
  • Python Infinite Loop
  • Python Loops
  • Python Multi Input
  • Python Range Function
  • Python Sequence
  • Python Sorting
  • Python Subplots
  • Python while else
  • Quicksort Python
  • R Programming Language
  • Race Condition
  • Ruby programming language
  • Runtime System
  • Scatter Chart Python
  • Secant Method
  • Shift Operator C
  • Single Structures In C
  • Singleton Pattern
  • Software Design Patterns
  • Statements in C
  • Storage Classes in C
  • String Formatting C
  • String in C
  • Strings in Python
  • Structures in C
  • Swift programming language
  • Syntax Errors
  • Threading In Computer Science
  • Variable Informatics
  • Variable Program
  • Variables in C
  • Version Control Systems
  • While Loop in C
  • Write Functions in C
  • exclusive or operation
  • for Loop in Python
  • if else in C
  • if else in Python
  • scanf Function with Buffered Input
  • switch Statement in C
  • while Loop in Python
  • Computer Systems
  • Data Representation in Computer Science
  • Data Structures
  • Functional Programming
  • Issues in Computer Science
  • Problem Solving Techniques
  • Theory of Computation

Assignment Operator in C Definition and Usage

The assignment operator in C is denoted with an equal sign (=) and is used to assign a value to a variable. The left operand is the variable, and the right operand is the value or expression to be assigned to that variable.

int main() { int x; x = 5; printf("The value of x is: %d", x); return 0; } ``` In this example, the assignment operator (=) assigns the value 5 to the variable x, which is then printed using the `printf()` function.

Basics of Assignment Operator in C

It is essential to understand basic usage and functionality of the assignment operator in C: - Variables must be declared before they can be assigned a value. - The data type on the right-hand side of the operator must be compatible with the data type of the variable on the left-hand side. Here are some more examples of using the assignment operator in C:

int a = 10; // Declare and assign in a single line float b = 3.14; char c = 'A';

Additionally, you can use the assignment operator with various arithmetic, relational, and logical operators:

`+=`: Add and assign

`-=`: Subtract and assign

`*=`: Multiply and assign

`/=`: Divide and assign

For example: int x = 5; x += 2; // Equivalent to x = x + 2; The value of x becomes 7

Importance of Assignment Operator in Computer Programming

The assignment operator in C plays a crucial role in computer programming. Its significance includes:

- Initialization of variables: The assignment operator is used to give an initial value to a variable, as demonstrated in the earlier examples.

- Modification of variable values: It allows you to change the value of a variable throughout the program. For example, you can use the assignment operator to increment the value of a counter variable in a loop.

- Expressions: The assignment operator is often used in expressions, such as calculating and storing the result of an arithmetic operation.

Example: Using the assignment operator with arithmetic operations:

#include int main() { int a = 10, b = 20, sum; sum = a + b; printf("The sum of a and b is: %d", sum); return 0; }

In this example, the assignment operator is used to store the result of the arithmetic operation `a + b` in the variable `sum`.

In conclusion, the assignment operator in C is an essential tool for computer programming. Understanding its definition, usage, and importance will significantly improve your programming skills and enable you to create more efficient and effective code.

Different Types of Assignment Operators in C

Compound assignment operators in c.

Compound assignment operators in C combine arithmetic, bit manipulation, or other operations with the basic assignment operator. This enables you to perform certain calculations and assignments of new values to variables in a single statement. Compound assignment operators are efficient, as they perform the operation and the assignment in one step rather than two separate steps. Let's examine the various compound assignment operators in C.

Addition Assignment Operator in C

The addition assignment operator (+=) in C combines the addition operation with the assignment operator, allowing you to increment the value of a variable by a specified amount. It essentially means "add the value of the right-hand side of the operator to the value of the variable on the left-hand side and then assign the new value to the variable". The general syntax for the addition assignment operator in C is: variable += value;

Using the addition assignment operator has some advantages:

- Reduces the amount of code you need: It is more concise and easier to read.

- Increases efficiency: It is faster because it performs the operation and assignment in one step.

Here's an example of the addition assignment operator in C: #include int main() { int a = 5; a += 3; // Equivalent to a = a + 3; The value of a becomes 8 printf("The value of a after addition assignment: %d, a); return 0; }

Compound assignment operators also include subtraction (-=), multiplication (*=), division (/=), modulo (%=), and bitwise operations like AND (&=), OR (|=), and XOR (^=). Their usage is similar to the addition assignment operator in C.

Assignment Operator for String in C

In C programming, strings are arrays of characters, and dealing with strings requires a careful approach. Direct assignment of a string using the assignment operator (=) is not possible, because arrays cannot be assigned using this operator. To assign a string to a character array, you need to use specific functions provided by the C language or develop your own custom function. Here are two commonly used methods for assigning a string to a character array:

1. Using the `strcpy()` function:

In this example, the `strcpy()` function from the `string.h` library is used to copy the contents of the `source` string into the `destination` character array.

2. Custom assignment function:

In this example, a custom function called `assignString()` is created to assign strings. It iterates through the characters of the `source` string, assigns each character to the corresponding element in the `destination` character array, and stops when it encounters the null character ('\0') at the end of the source string. Understanding assignment operators in C and the various types of assignment operators can help you write more efficient and effective code. It also enables you to work effectively with different data types, including strings and arrays of characters, which are essential for creating powerful and dynamic software applications.

Practical Examples of Assignment Operator in C

In this section, we will explore some practical examples of the assignment operator in C. Examples will cover simple assignments and discuss usage scenarios for compound assignment operators, as well as demonstrating the implementation of the assignment operator for strings in C.

Assignment Operator in C Example: Simple Assignments

Simple assignment operations in C involve assigning a single value to a variable. Here are some examples of simple assignment operations:

1. Assigning an integer value to a variable: int age = 25;

2. Assigning a floating-point value to a variable: float salary = 50000.75;

3. Assigning a character value to a variable: char grade = 'A';

4. Swapping the values of two variables:

In this swapping example, the assignment operator is used to temporarily store the value of one variable and then exchange the values of two variables.

Usage Scenarios for Compound Assignment Operators

Compound assignment operators in C provide shorthand ways of updating the values of variables with arithmetic, bitwise, or other operations. Here are some common usage scenarios for compound assignment operators:

1. Incrementing a counter variable in a loop: for(int i = 0; i < 10; i += 2) { printf("%d ", i); } Here, the addition assignment operator (+=) is used within a `for` loop to increment the counter variable `i` by 2 at each iteration.

2. Accumulating the sum of elements in an array: #include int main() { int array[] = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < 5; i++) { sum += array[i]; // Equivalent to sum = sum + array[i]; } printf("Sum of array elements: %d", sum); return 0; } In this example, the addition assignment operator (+=) is used to accumulate the sum of the array elements.

3. Calculating the product of two numbers using bitwise operations:

I n this example, the bitwise AND operation is combined with the addition assignment operator (+=) along with bitwise shift and compound assignment operators to perform multiplication without using the arithmetic `*` operator.

Implementing Assignment Operator for String in C with Examples

As discussed earlier, assigning strings in C requires a different approach, as the assignment operator (=) cannot be used directly. Here are some practical examples that demonstrate how to implement the assignment operator for strings in C:

1. Using the `strcpy()` function from the `string.h` library:

2. Defining a custom function to assign strings, which takes two character pointers as arguments:

These examples showcase the implementation of the assignment operator for strings in C, enabling you to effectively manipulate and work with strings in your C programs. By using built-in C functions or defining your own custom functions, you can assign strings to character arrays, which allow you to perform various operations on strings, such as concatenation, comparison, substring search, and more.

Assignment Operator in C - Key takeaways

Assignment Operator in C: represented by the equal sign (=), assigns a value to a variable

Compound assignment operators in C: combine arithmetic or bitwise operations with the assignment operator, such as +=, -=, and *=

Addition assignment operator in C: represented by (+=), adds a value to an existing variable and assigns the new value

Assignment operator for string in C : requires specific functions like strcpy() or custom functions, as direct assignment with = is not possible

Assignment Operator in C example: int x = 5; assigns the value 5 to the variable x

Flashcards in Assignment Operator in C 11

What symbol is used as the assignment operator in C programming?

An equal sign (=)

What is the syntax for the addition assignment operator in C?

variable += value;

What is the compound assignment operator for multiplication in C?

Why is direct assignment of a string using the assignment operator (=) not possible in C?

Arrays cannot be assigned using the assignment operator.

How can a string be assigned to a character array using the `strcpy()` function in C?

GetString(destination, source);

Which function or method can be used to assign a string to a character array in C programming?

Using the `strcpy()` function or a custom assignment function.

Assignment Operator in C

Learn with 11 Assignment Operator in C flashcards in the free Vaia app

We have 14,000 flashcards about Dynamic Landscapes.

Already have an account? Log in

Frequently Asked Questions about Assignment Operator in C

Test your knowledge with multiple choice flashcards.

Assignment Operator in C

Join the Vaia App and learn efficiently with millions of flashcards and more!

Keep learning, you are doing great.

Discover learning materials with the free Vaia app

1

Vaia is a globally recognized educational technology company, offering a holistic learning platform designed for students of all ages and educational levels. Our platform provides learning support for a wide range of subjects, including STEM, Social Sciences, and Languages and also helps students to successfully master various tests and exams worldwide, such as GCSE, A Level, SAT, ACT, Abitur, and more. We offer an extensive library of learning materials, including interactive flashcards, comprehensive textbook solutions, and detailed explanations. The cutting-edge technology and tools we provide help students create their own learning materials. StudySmarter’s content is not only expert-verified but also regularly updated to ensure accuracy and relevance.

Assignment Operator in C

Vaia Editorial Team

Team Assignment Operator in C Teachers

  • 10 minutes reading time
  • Checked by Vaia Editorial Team

Study anywhere. Anytime.Across all devices.

Create a free account to save this explanation..

Save explanations to your personalised space and access them anytime, anywhere!

By signing up, you agree to the Terms and Conditions and the Privacy Policy of Vaia.

Sign up to highlight and take notes. It’s 100% free.

Join over 22 million students in learning with our Vaia App

The first learning app that truly has everything you need to ace your exams in one place

  • Flashcards & Quizzes
  • AI Study Assistant
  • Study Planner
  • Smart Note-Taking

Join over 22 million students in learning with our Vaia App

Privacy Overview

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.

Learn to Code, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Mostly Asked C Interview Questions and Answers

02 Beginner

  • If Statement in C
  • Understanding do...while loop in C
  • Understanding for loop in C
  • if else if statements in C Programming
  • If...else statement in C Programming
  • Understanding realloc() function in C
  • Understanding While loop in C
  • Why C is called middle level language?
  • Beginner's Guide to C Programming
  • First C program and Its Syntax
  • Escape Sequences and Comments in C
  • Keywords in C: List of Keywords
  • Identifiers in C: Types of Identifiers
  • Data Types in C Programming - A Beginner Guide with examples
  • Variables in C Programming - Types of Variables in C ( With Examples )
  • 10 Reasons Why You Should Learn C
  • Boolean and Static in C Programming With Examples ( Full Guide )
  • Operators in C: Types of Operators
  • Bitwise Operators in C: AND, OR, XOR, Shift & Complement
  • Expressions in C Programming - Types of Expressions in C ( With Examples )
  • Conditional Statements in C: if, if..else, Nested if
  • Switch Statement in C: Syntax and Examples
  • Ternary Operator in C: Ternary Operator vs. if...else Statement
  • Loop in C with Examples: For, While, Do..While Loops
  • Nested Loops in C - Types of Expressions in C ( With Examples )
  • Infinite Loops in C: Types of Infinite Loops
  • Jump Statements in C: break, continue, goto, return
  • Continue Statement in C: What is Break & Continue Statement in C with Example

03 Intermediate

  • Constants in C language
  • Getting Started with Data Structures in C
  • Functions in C Programming
  • Call by Value and Call by Reference in C
  • Recursion in C: Types, its Working and Examples
  • Storage Classes in C: Auto, Extern, Static, Register
  • Arrays in C Programming: Operations on Arrays
  • Strings in C with Examples: String Functions

04 Advanced

  • How to Dynamically Allocate Memory using calloc() in C?
  • How to Dynamically Allocate Memory using malloc() in C?
  • Pointers in C: Types of Pointers
  • Multidimensional Arrays in C: 2D and 3D Arrays
  • Dynamic Memory Allocation in C: Malloc(), Calloc(), Realloc(), Free()

05 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • C Programming Course
  • Data Structures and Algorithms Training
  • C Programming Assignment ..

C Programming Assignment Operators

C Programming Assignment Operators

compound assignment operators in c with example

C Programming For Beginners Free Course

What is an assignment operator in c.

Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as they require two operands to operate upon. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=". The value on the right side must be of the same data type as the variable on the left side. Hence, the associativity is from right to left.

In this C tutorial , we'll understand the types of C programming assignment operators with examples. To delve deeper you can enroll in our C Programming Course .

Before going in-depth about assignment operators you must know about operators in C. If you haven't visited the Operators in C tutorial, refer to Operators in C: Types of Operators .

Types of Assignment Operators in C

There are two types of assignment operators in C:

Types of Assignment Operators in C
+=addition assignmentIt adds the right operand to the left operand and assigns the result to the left operand.
-=subtraction assignmentIt subtracts the right operand from the left operand and assigns the result to the left operand.
*=multiplication assignmentIt multiplies the right operand with the left operand and assigns the result to the left operand
/=division assignmentIt divides the left operand with the right operand and assigns the result to the left operand.
%=modulo assignmentIt takes modulus using two operands and assigns the result to the left operand.

Example of Augmented Arithmetic and Assignment Operators

There can be five combinations of bitwise operators with the assignment operator, "=". Let's look at them one by one.

&=bitwise AND assignmentIt performs the bitwise AND operation on the variable with the value on the right
|=bitwise OR assignmentIt performs the bitwise OR operation on the variable with the value on the right
^=bitwise XOR assignmentIt performs the bitwise XOR operation on the variable with the value on the right
<<=bitwise left shift assignmentShifts the bits of the variable to the left by the value on the right
>>=bitwise right shift assignmentShifts the bits of the variable to the right by the value on the right

Example of Augmented Bitwise and Assignment Operators

Practice problems on assignment operators in c, 1. what will the value of "x" be after the execution of the following code.

The correct answer is 52. x starts at 50, increases by 5 to 55, then decreases by 3 to 52.

2. After executing the following code, what is the value of the number variable?

The correct answer is 144. After right-shifting 73 (binary 1001001) by one and then left-shifting the result by two, the value becomes 144 (binary 10010000).

Benefits of Using Assignment Operators

  • Simplifies Code: For example, x += 1 is shorter and clearer than x = x + 1.
  • Reduces Errors: They break complex expressions into simpler, more manageable parts thus reducing errors.
  • Improves Readability: They make the code easier to read and understand by succinctly expressing common operations.
  • Enhances Performance: They often operate in place, potentially reducing the need for additional memory or temporary variables.

Best Practices and Tips for Using the Assignment Operator

While performing arithmetic operations with the same variable, use compound assignment operators

  • Initialize Variables When Declaring int count = 0 ; // Initialization
  • Avoid Complex Expressions in Assignments a = (b + c) * (d - e); // Consider breaking it down: int temp = b + c; a = temp * (d - e);
  • Avoid Multiple Assignments in a Single Statement // Instead of this a = b = c = 0 ; // Do this a = 0 ; b = 0 ; c = 0 ;
  • Consistent Formatting int result = 0 ; result += 10 ;

When mixing assignments with other operations, use parentheses to ensure the correct order of evaluation.

Live Classes Schedule

ASP.NET Core Certification Training Jun 14 MON, WED, FRI Filling Fast
Advanced Full-Stack .NET Developer Certification Training Jun 14 MON, WED, FRI Filling Fast
Angular Certification Course Jun 16 SAT, SUN Filling Fast
ASP.NET Core (Project) Jun 23 SAT, SUN Filling Fast
Azure Developer Certification Training Jun 23 SAT, SUN Filling Fast
Generative AI For Software Developers Jun 23 SAT, SUN Filling Fast
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN Filling Fast

Can't find convenient schedule? Let us know

About Author

Author image

  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

What is the difference between += and =+ C assignment operators [duplicate]

I was wondering if there was a difference between =+ and += (and other assignment operators too). I tried and both did the same thing. So is there a difference or is there a convention? Do both work because my compilers dont check for standarts?

Edit: I made a mistake. I used bad inputs during my testing which led me to thinking they are both doing the same thing. Turns out they are two different things.

+= adds rvalue to lvalue

=+ assigns rvalue to lvalue

  • assignment-operator
  • compound-assignment

Michael's user avatar

  • 16 There is no =+ operator in C. –  Eugene Sh. Jan 12, 2017 at 15:07
  • 6 I works as two different operators. Assignment and unary + . –  Eugene Sh. Jan 12, 2017 at 15:08
  • 9 @EugeneSh.: strictly, there is no longer a =+ operator in C. It ceased to be a part of C in the mid-70s. Note that =+ , =- , =& can both appear in modern C — even =* if the term following is a pointer. Most of the others can't. However, the meaning is of the two separate operators; the fact that they're touching is immaterial. –  Jonathan Leffler Jan 12, 2017 at 15:13
  • 2 If you have: int main(void) { int i = 2, j = 3; i =+ j; printf("%d\n", i); return 0; } , do you get 3 or 5 printed? Standard C says it should be 3. Even I've never worked with a compiler that gives a different result — the change from the original =+ to += occurred years before I started coding in C. –  Jonathan Leffler Jan 12, 2017 at 15:16
  • 1 @SunggukLim: There's nothing surprising about that. =+ is two operators, = and + . See my answer for details. –  Keith Thompson May 31, 2018 at 17:48

In modern C, or even moderately ancient C, += is a compound assignment operator, and =+ is parsed as two separate tokens. = and + . Punctuation tokens are allowed to be adjacent.

So if you write:

it's equivalent to

except that x is only evaluated once (which can matter if it's a more complicated expression).

If you write:

then it's parsed as

and the + is a unary plus operator.

Very early versions of C (around the mid 1970s, before the publication of K&R1 in 1978) used different symbols for compound assignments. Where modern C uses += , early C used =+ . Early C had no unary + operator, but it did have a unary - operator, and the use of =- caused problems; programmers would write x=-y intending it to mean x = -y , but it was silently interpreted as x =- y . The language was changed some time between 1975 and 1978 to avoid that problem. As late as 1999, I worked with a compiler (VAXC on VMS) that would warn about an ambiguous use of =- , but would use the older meaning. That shouldn't be a concern now unless you're a hobbyist playing with some very old software and/or hardware.

(A 1975 C Reference Manual shows the old =- , =+ , et al forms of the compound assignment operators. The first edition of The C Programming Language by Kernighan and Ritchie, published in 1978, shows the modern -= , += , et al, but mentions the older forms under "Anachronisms".)

Keith Thompson's user avatar

  • 2 To this day I still put a space after the = so a = -7; is not misinterpreted as a -= 7; . –  chux - Reinstate Monica Mar 28, 2020 at 22:48
  • 1 @chux-ReinstateMonica So do I, but only because I find it more legible. –  Keith Thompson Mar 28, 2020 at 23:16

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

  • Featured on Meta
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • The [tax] tag is being burninated
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • What are these cylinders with holes for in a universal PCB enclosure?
  • Mismatching Euler characteristic of the Torus
  • Looking for some words or phrases
  • My players think they found a loophole that gives them infinite poison and XP. How can I add the proper challenges to slow them down?
  • Can we combine a laser with a gauss rifle to get a cinematic 'laser rifle'?
  • Smallest Harmonic number greater than N
  • How do Authenticators work?
  • Have I ruined my AC by running it with the outside cover on?
  • Was it known in ancient Rome and Greece that boiling water made it safe to drink and if so, what was the theory behind this?
  • Is it allowed to use patents for new inventions?
  • Has there ever been arms supply with restrictions attached prior to the current war in Ukraine?
  • Commutativity of the wreath product
  • Can you use the special use features with tools without the tool?
  • Yosemite national park availability
  • I am international anyway
  • Movie I saw in the 80s where a substance oozed off of movie stairs leaving a wet cat behind
  • Why is "second" an adverb in "came a close second"?
  • In the Unabomber case, was "call Nathan R" really mistakenly written by a New York Times intern?
  • Improvising if I don't hear anything in my "mind's ear"?
  • How does Wolfram Alpha know this closed form?
  • Using command defined with \NewDocumentCommand in TikZ
  • A short story in French about furniture that leaves a mansion by itself, and comes back some time later
  • Expected Amp difference going from SEU-AL to Copper on HVAC?
  • Starlink Satellite Orbits

compound assignment operators in c with example

cppreference.com

Assignment operators.

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

    

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

expression
pointer
specifier

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

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

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

Assignment operators modify the value of the object.

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

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

[ edit ] Definitions

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

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

(since C++11)

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

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

[ edit ] Assignment operator syntax

The assignment expressions have the form

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

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

(since C++11)

[ edit ] Built-in simple assignment operator

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

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

[ edit ] Assignment from an expression

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

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

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

(since C++20)

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

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

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

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

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

operator=(T&, T);

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

operator=(A1&, A2);

[ edit ] Built-in compound assignment operator

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

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

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

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

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

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

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

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

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

[ edit ] Example

Possible output:

[ edit ] Defect reports

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

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

[ edit ] See also

Operator precedence

Operator overloading

Common operators

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

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

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

!a
a && b
a || b

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

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

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

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

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

Powered by MediaWiki

compound assignment operators in c with example

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Getting Started
  • 1.1.1 Preface
  • 1.1.2 About the AP CSA Exam
  • 1.1.3 Transitioning from AP CSP to AP CSA
  • 1.1.4 Java Development Environments
  • 1.1.5 Growth Mindset and Pair Programming
  • 1.1.6 Pretest for the AP CSA Exam
  • 1.1.7 Survey
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Values
  • 1.7 Unit 1 Summary
  • 1.8 Mixed Up Code Practice
  • 1.9 Toggle Mixed Up or Write Code Practice
  • 1.10 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.4. Expressions and Assignment Statements" data-toggle="tooltip">
  • 1.6. Casting and Ranges of Values' data-toggle="tooltip" >

Time estimate: 45 min.

1.5. Compound Assignment Operators ¶

Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x . It is the same as x = x + 1 . This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound operators are written like += or =+ , just remember that the operation ( + ) is done first to produce the new value which is then assigned ( = ) back to the variable. So it’s operator then equal sign: += .

Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and -- , also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.

Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1 . You’ll see this shortcut used a lot in loops when we get to them in Unit 4. Similarly, y-- is a more concise way to write y = y - 1 . These shortcuts only exist for + and - as they don’t really make sense for other operators.

If you’ve heard of the programming language C++, the name is an inside joke that C, an earlier language which C++ is based on, had been incremented or improved to create C++.

Here’s a table of all the compound arithmetic operators and the extra concise incremend and decrement operators and how they relate to fully written out assignment expressions. You can run the code below the table to see these shortcut operators in action!

Operator

Written out

= x + 1

= x - 1

= x * 2

= x / 2

= x % 2

Compound

+= 1

-= 1

*= 2

/= 2

%= 2

Extra concise

Run the code below to see what the ++ and shorcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Try creating more compound assignment statements with shortcut operators and work with a partner to guess what they would print out before running the code.

If you look at real-world Java code, you may occassionally see the ++ and -- operators used before the name of the variable, like ++x rather than x++ . That is legal but not something that you will see on the AP exam.

Putting the operator before or after the variable only changes the value of the expression itself. If x is 10 and we write, System.out.println(x++) it will print 10 but aftewards x will be 11. On the other hand if we write, System.out.println(++x) , it will print 11 and afterwards the value will be 11.

In other words, with the operator after the variable name, (called the postfix operator) the value of the variable is changed after evaluating the variable to get its value. And with the operator before the variable (the prefix operator) the value of the variable in incremented before the variable is evaluated to get the value of the expression.

But the value of x after the expression is evaluated is the same in either case: one greater than what it was before. The -- operator works similarly.

The AP exam will never use the prefix form of these operators nor will it use the postfix operators in a context where the value of the expression matters.

exercise

1-5-2: What are the values of x, y, and z after the following code executes?

  • x = -1, y = 1, z = 4
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 3
  • x = -1, y = 2, z = 2
  • x = 0, y = 1, z = 2
  • x = -1, y = 2, z = 4

1-5-3: What are the values of x, y, and z after the following code executes?

  • x = 6, y = 2.5, z = 2
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2.5, z = 2
  • x = 6, y = 2, z = 3
  • x = 4, y = 2.5, z = 3
  • x = 4, y = 2, z = 3

1.5.1. Code Tracing Challenge and Operators Maze ¶

Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end.

Code Tracing is a technique used to simulate a dry run through the code or pseudocode line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.

Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.

../_images/traceTable.png

Trace through the following code:

1-5-4: Write your trace table for x, y, and z here showing their results after each line of code.

After doing this challenge, play the Operators Maze game . See if you and your partner can get the highest score!

1.5.2. Summary ¶

Compound assignment operators ( += , -= , *= , /= , %= ) can be used in place of the assignment operator.

The increment operator ( ++ ) and decrement operator ( -- ) are used to add 1 or subtract 1 from the stored value of a variable. The new value is assigned to the variable.

The use of increment and decrement operators in prefix form (e.g., ++x ) and inside other expressions (i.e., arr[x++] ) is outside the scope of this course and the AP Exam.

  • C++ Language
  • Ascii Codes
  • Boolean Operations
  • Numerical Bases

Introduction

Basics of c++.

  • Structure of a program
  • Variables and types
  • Basic Input/Output

Program structure

  • Statements and flow control
  • Overloads and templates
  • Name visibility

Compound data types

  • Character sequences
  • Dynamic memory
  • Data structures
  • Other data types
  • Classes (I)
  • Classes (II)
  • Special members
  • Friendship and inheritance
  • Polymorphism

Other language features

  • Type conversions
  • Preprocessor directives

Standard library

  • Input/output with files

Assignment operator (=)

std; main () { a, b; a = 10; b = 4; a = b; b = 7; cout << ; cout << a; cout << ; cout << b; }

Arithmetic operators ( +, -, *, /, % )

operatordescription
addition
subtraction
multiplication
division
modulo

Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

expressionequivalent to...
std; main () { a, b=3; a = b; a+=2; cout << a; }

Increment and decrement (++, --)

Example 1Example 2

Relational and comparison operators ( ==, !=, >, <, >=, <= )

operatordescription
Equal to
Not equal to
Less than
Greater than
Less than or equal to
Greater than or equal to
(5 > 4) (3 != 2) (6 >= 6) (5 < 5)
(a*b >= c) (b+4 > a*c) ((b=2) == a)

Logical operators ( !, &&, || )

!(6 <= 4) ! !
&& OPERATOR (and)
|| OPERATOR (or)
( (5 == 5) || (3 > 6) )
operatorshort-circuit
if the left-hand side expression is , the combined result is (the right-hand side expression is never evaluated).
if the left-hand side expression is , the combined result is (the right-hand side expression is never evaluated).
( (i<10) && (++i<n) ) { }

Conditional ternary operator ( ? )

7==5+2 ? 4 : 3 5>3 ? a : b a>b ? a : b
std; main () { a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << c << ; }

Comma operator ( , )

Bitwise operators ( &, |, ^, ~, <<, >> ).

operatorasm equivalentdescription
Bitwise AND
Bitwise inclusive OR
Bitwise exclusive OR
Unary complement (bit inversion)
Shift bits left
Shift bits right

Explicit type casting operator

i; f = 3.14; i = ( ) f;
(f);
( );

Other operators

Precedence of operators.

x = (5 + 7) % 2;
LevelPrecedence groupOperatorDescriptionGrouping
1Scope scope qualifierLeft-to-right
2Postfix (unary) postfix increment / decrementLeft-to-right
functional forms
subscript
member access
3Prefix (unary) prefix increment / decrementRight-to-left
bitwise NOT / logical NOT
unary prefix
reference / dereference
allocation / deallocation
parameter pack
)C-style type-casting
4Pointer-to-member access pointerLeft-to-right
5Arithmetic: scaling multiply, divide, moduloLeft-to-right
6Arithmetic: addition addition, subtractionLeft-to-right
7Bitwise shift shift left, shift rightLeft-to-right
8Relational comparison operatorsLeft-to-right
9Equality equality / inequalityLeft-to-right
10And bitwise ANDLeft-to-right
11Exclusive or bitwise XORLeft-to-right
12Inclusive or bitwise ORLeft-to-right
13Conjunction logical ANDLeft-to-right
14Disjunction logical ORLeft-to-right
15Assignment-level expressions assignment / compound assignmentRight-to-left
conditional operator
16Sequencing comma separatorLeft-to-right

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Compound Assignment Operators in C++

The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −

  • An arithmetic type
  • A pointer, if op is + or –

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

The following are the compound assignment operators in C++ −

Operators
Description
*=
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.

Let's have a look at an example using some of these operators −

This will give the output −

Note that 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. If the left operand is of an integral type, the right operand must not be of a pointer type.

Govinda Sai

Related Articles

  • Compound assignment operators in C#
  • Compound assignment operators in Java\n
  • Assignment Operators in C++
  • What are assignment operators in C#?
  • Perl Assignment Operators
  • Assignment operators in Dart Programming
  • Compound operators in Arduino
  • What is the difference between = and: = assignment operators?
  • Passing the Assignment in C++
  • Airplane Seat Assignment Probability in C++
  • What is an assignment operator in C#?
  • Copy constructor vs assignment operator in C++
  • Unary operators in C/C++
  • Ternary Operators in C/C++
  • Arithmetic Operators in C++

Kickstart Your Career

Get certified by completing the course

To Continue Learning Please Login

Find Study Materials for

  • Explanations
  • Business Studies
  • Combined Science
  • Engineering
  • English Literature
  • Environmental Science
  • Human Geography
  • Macroeconomics
  • Microeconomics
  • Social Studies
  • Browse all subjects
  • Read our Magazine

Create Study Materials

  • Flashcards Create and find the best flashcards.
  • Notes Create notes faster than ever before.
  • Study Sets Everything you need for your studies in one place.
  • Study Plans Stop procrastinating with our smart planner features.
  • Assignment Operator in C

In the realm of computer programming , specifically in the C programming language, understanding and utilising assignment operators effectively is essential for developing efficient and well-organised code. The assignment operator in C plays a fundamental role in assigning values to variables, and this introductory piece will elaborate on its definition, usage and importance. Gain insights on different types of assignment operators, such as compound assignment operators and the assignment operator for strings in C. As you delve deeper, practical examples of the assignment operator in C will be provided, enabling you to gain a firm grasp on the concept and apply this knowledge for successful programming endeavours.

Assignment Operator in C

Create learning materials about Assignment Operator in C with our free learning app!

  • Instand access to millions of learning materials
  • Flashcards, notes, mock-exams and more
  • Everything you need to ace your exams
  • Algorithms in Computer Science
  • Computer Network
  • Computer Organisation and Architecture
  • Computer Programming
  • 2d Array in C
  • AND Operator in C
  • Access Modifiers
  • Actor Model
  • Algorithm in C
  • Array as function argument in c
  • Automatically Creating Arrays in Python
  • Bitwise Operators in C
  • C Arithmetic Operations
  • C Array of Structures
  • C Functions
  • C Math Functions
  • C Memory Address
  • C Plus Plus
  • C Program to Find Roots of Quadratic Equation
  • C Programming Language
  • Change Data Type in Python
  • Classes in Python
  • Comments in C
  • Common Errors in C Programming
  • Compound Statement in C
  • Concurrency Vs Parallelism
  • Concurrent Programming
  • Conditional Statement
  • Critical Section
  • Data Types in Programming
  • Declarative Programming
  • Decorator Pattern
  • Distributed Programming
  • Do While Loop in C
  • Dynamic allocation of array in c
  • Encapsulation programming
  • Event Driven Programming
  • Exception Handling
  • Executable File
  • Factory Pattern
  • For Loop in C
  • Formatted Output in C
  • Functions in Python
  • How to return multiple values from a function in C
  • Identity Operator in Python
  • Imperative programming
  • Increment and Decrement Operators in C
  • Inheritance in Oops
  • Insertion Sort Python
  • Instantiation
  • Integrated Development Environments
  • Integration in C
  • Interpreter Informatics
  • Java Abstraction
  • Java Annotations
  • Java Arithmetic Operators
  • Java Arraylist
  • Java Arrays
  • Java Assignment Operators
  • Java Bitwise Operators
  • Java Classes And Objects
  • Java Collections Framework
  • Java Constructors
  • Java Data Types
  • Java Do While Loop
  • Java Enhanced For Loop
  • Java Expection Handling
  • Java File Class
  • Java File Handling
  • Java Finally
  • Java For Loop
  • Java Function
  • Java Generics
  • Java IO Package
  • Java If Else Statements
  • Java If Statements
  • Java Inheritance
  • Java Interfaces
  • Java List Interface
  • Java Logical Operators
  • Java Map Interface
  • Java Method Overloading
  • Java Method Overriding
  • Java Multidimensional Arrays
  • Java Multiple Catch Blocks
  • Java Nested If
  • Java Nested Try
  • Java Non Primitive Data Types
  • Java Operators
  • Java Polymorphism
  • Java Primitive Data Types
  • Java Queue Interface
  • Java Recursion
  • Java Reflection
  • Java Relational Operators
  • Java Set Interface
  • Java Single Dimensional Arrays
  • Java Statements
  • Java Static Keywords
  • Java Switch Statement
  • Java Syntax
  • Java This Keyword
  • Java Try Catch
  • Java Type Casting
  • Java Virtual Machine
  • Java While Loop
  • Javascript Anonymous Functions
  • Javascript Arithmetic Operators
  • Javascript Array Methods
  • Javascript Array Sort
  • Javascript Arrays
  • Javascript Arrow Functions
  • Javascript Assignment Operators
  • Javascript Async
  • Javascript Asynchronous Programming
  • Javascript Await
  • Javascript Bitwise Operators
  • Javascript Callback
  • Javascript Callback Functions
  • Javascript Changing Elements
  • Javascript Classes
  • Javascript Closures
  • Javascript Comparison Operators
  • Javascript DOM Events
  • Javascript DOM Manipulation
  • Javascript Data Types
  • Javascript Do While Loop
  • Javascript Document Object
  • Javascript Event Loop
  • Javascript For In Loop
  • Javascript For Loop
  • Javascript For Of Loop
  • Javascript Function
  • Javascript Function Expressions
  • Javascript Hoisting
  • Javascript If Else Statement
  • Javascript If Statement
  • Javascript Immediately Invoked Function Expressions
  • Javascript Inheritance
  • Javascript Interating Arrays
  • Javascript Logical Operators
  • Javascript Loops
  • Javascript Multidimensional Arrays
  • Javascript Object Creation
  • Javascript Object Prototypes
  • Javascript Objects
  • Javascript Operators
  • Javascript Primitive Data Types
  • Javascript Promises
  • Javascript Reference Data Types
  • Javascript Scopes
  • Javascript Selecting Elements
  • Javascript Spread And Rest
  • Javascript Statements
  • Javascript Strict Mode
  • Javascript Switch Statement
  • Javascript Syntax
  • Javascript Ternary Operator
  • Javascript This Keyword
  • Javascript Type Conversion
  • Javascript While Loop
  • Linear Equations in C
  • Log Plot Python
  • Logical Error
  • Logical Operators in C
  • Loop in programming
  • Matrix Operations in C
  • Membership Operator in Python
  • Model View Controller
  • Nested Loops in C
  • Nested if in C
  • Numerical Methods in C
  • OR Operator in C
  • Object orientated programming
  • Observer Pattern
  • One Dimensional Arrays in C
  • Oops concepts
  • Operators in Python
  • Parameter Passing
  • Pascal Programming Language
  • Plot in Python
  • Plotting In Python
  • Pointer Array C
  • Pointers and Arrays
  • Pointers in C
  • Polymorphism programming
  • Procedural Programming
  • Programming Control Structures
  • Programming Language PHP
  • Programming Languages
  • Programming Paradigms
  • Programming Tools
  • Python Arithmetic Operators
  • Python Array Operations
  • Python Arrays
  • Python Assignment Operator
  • Python Bar Chart
  • Python Bitwise Operators
  • Python Bubble Sort
  • Python Comparison Operators
  • Python Data Types
  • Python Indexing
  • Python Infinite Loop
  • Python Loops
  • Python Multi Input
  • Python Range Function
  • Python Sequence
  • Python Sorting
  • Python Subplots
  • Python while else
  • Quicksort Python
  • R Programming Language
  • Race Condition
  • Ruby programming language
  • Runtime System
  • Scatter Chart Python
  • Secant Method
  • Shift Operator C
  • Single Structures In C
  • Singleton Pattern
  • Software Design Patterns
  • Statements in C
  • Storage Classes in C
  • String Formatting C
  • String in C
  • Strings in Python
  • Structures in C
  • Swift programming language
  • Syntax Errors
  • Threading In Computer Science
  • Variable Informatics
  • Variable Program
  • Variables in C
  • Version Control Systems
  • While Loop in C
  • Write Functions in C
  • exclusive or operation
  • for Loop in Python
  • if else in C
  • if else in Python
  • scanf Function with Buffered Input
  • switch Statement in C
  • while Loop in Python
  • Computer Systems
  • Data Representation in Computer Science
  • Data Structures
  • Functional Programming
  • Issues in Computer Science
  • Problem Solving Techniques
  • Theory of Computation

Assignment Operator in C Definition and Usage

The assignment operator in C is denoted with an equal sign (=) and is used to assign a value to a variable. The left operand is the variable, and the right operand is the value or expression to be assigned to that variable.

int main() { int x; x = 5; printf("The value of x is: %d", x); return 0; } ``` In this example, the assignment operator (=) assigns the value 5 to the variable x, which is then printed using the `printf()` function.

Basics of Assignment Operator in C

It is essential to understand basic usage and functionality of the assignment operator in C: - Variables must be declared before they can be assigned a value. - The data type on the right-hand side of the operator must be compatible with the data type of the variable on the left-hand side. Here are some more examples of using the assignment operator in C:

int a = 10; // Declare and assign in a single line float b = 3.14; char c = 'A';

Additionally, you can use the assignment operator with various arithmetic, relational, and logical operators:

`+=`: Add and assign

`-=`: Subtract and assign

`*=`: Multiply and assign

`/=`: Divide and assign

For example: int x = 5; x += 2; // Equivalent to x = x + 2; The value of x becomes 7

Importance of Assignment Operator in Computer Programming

The assignment operator in C plays a crucial role in computer programming. Its significance includes:

- Initialization of variables: The assignment operator is used to give an initial value to a variable, as demonstrated in the earlier examples.

- Modification of variable values: It allows you to change the value of a variable throughout the program. For example, you can use the assignment operator to increment the value of a counter variable in a loop.

- Expressions: The assignment operator is often used in expressions, such as calculating and storing the result of an arithmetic operation.

Example: Using the assignment operator with arithmetic operations:

#include int main() { int a = 10, b = 20, sum; sum = a + b; printf("The sum of a and b is: %d", sum); return 0; }

In this example, the assignment operator is used to store the result of the arithmetic operation `a + b` in the variable `sum`.

In conclusion, the assignment operator in C is an essential tool for computer programming. Understanding its definition, usage, and importance will significantly improve your programming skills and enable you to create more efficient and effective code.

Different Types of Assignment Operators in C

Compound assignment operators in c.

Compound assignment operators in C combine arithmetic, bit manipulation, or other operations with the basic assignment operator. This enables you to perform certain calculations and assignments of new values to variables in a single statement. Compound assignment operators are efficient, as they perform the operation and the assignment in one step rather than two separate steps. Let's examine the various compound assignment operators in C.

Addition Assignment Operator in C

The addition assignment operator (+=) in C combines the addition operation with the assignment operator, allowing you to increment the value of a variable by a specified amount. It essentially means "add the value of the right-hand side of the operator to the value of the variable on the left-hand side and then assign the new value to the variable". The general syntax for the addition assignment operator in C is: variable += value;

Using the addition assignment operator has some advantages:

- Reduces the amount of code you need: It is more concise and easier to read.

- Increases efficiency: It is faster because it performs the operation and assignment in one step.

Here's an example of the addition assignment operator in C: #include int main() { int a = 5; a += 3; // Equivalent to a = a + 3; The value of a becomes 8 printf("The value of a after addition assignment: %d, a); return 0; }

Compound assignment operators also include subtraction (-=), multiplication (*=), division (/=), modulo (%=), and bitwise operations like AND (&=), OR (|=), and XOR (^=). Their usage is similar to the addition assignment operator in C.

Assignment Operator for String in C

In C programming, strings are arrays of characters, and dealing with strings requires a careful approach. Direct assignment of a string using the assignment operator (=) is not possible, because arrays cannot be assigned using this operator. To assign a string to a character array, you need to use specific functions provided by the C language or develop your own custom function. Here are two commonly used methods for assigning a string to a character array:

1. Using the `strcpy()` function:

In this example, the `strcpy()` function from the `string.h` library is used to copy the contents of the `source` string into the `destination` character array.

2. Custom assignment function:

In this example, a custom function called `assignString()` is created to assign strings. It iterates through the characters of the `source` string, assigns each character to the corresponding element in the `destination` character array, and stops when it encounters the null character ('\0') at the end of the source string. Understanding assignment operators in C and the various types of assignment operators can help you write more efficient and effective code. It also enables you to work effectively with different data types, including strings and arrays of characters, which are essential for creating powerful and dynamic software applications.

Practical Examples of Assignment Operator in C

In this section, we will explore some practical examples of the assignment operator in C. Examples will cover simple assignments and discuss usage scenarios for compound assignment operators, as well as demonstrating the implementation of the assignment operator for strings in C.

Assignment Operator in C Example: Simple Assignments

Simple assignment operations in C involve assigning a single value to a variable. Here are some examples of simple assignment operations:

1. Assigning an integer value to a variable: int age = 25;

2. Assigning a floating-point value to a variable: float salary = 50000.75;

3. Assigning a character value to a variable: char grade = 'A';

4. Swapping the values of two variables:

In this swapping example, the assignment operator is used to temporarily store the value of one variable and then exchange the values of two variables.

Usage Scenarios for Compound Assignment Operators

Compound assignment operators in C provide shorthand ways of updating the values of variables with arithmetic, bitwise, or other operations. Here are some common usage scenarios for compound assignment operators:

1. Incrementing a counter variable in a loop: for(int i = 0; i < 10; i += 2) { printf("%d ", i); } Here, the addition assignment operator (+=) is used within a `for` loop to increment the counter variable `i` by 2 at each iteration.

2. Accumulating the sum of elements in an array: #include int main() { int array[] = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < 5; i++) { sum += array[i]; // Equivalent to sum = sum + array[i]; } printf("Sum of array elements: %d", sum); return 0; } In this example, the addition assignment operator (+=) is used to accumulate the sum of the array elements.

3. Calculating the product of two numbers using bitwise operations:

I n this example, the bitwise AND operation is combined with the addition assignment operator (+=) along with bitwise shift and compound assignment operators to perform multiplication without using the arithmetic `*` operator.

Implementing Assignment Operator for String in C with Examples

As discussed earlier, assigning strings in C requires a different approach, as the assignment operator (=) cannot be used directly. Here are some practical examples that demonstrate how to implement the assignment operator for strings in C:

1. Using the `strcpy()` function from the `string.h` library:

2. Defining a custom function to assign strings, which takes two character pointers as arguments:

These examples showcase the implementation of the assignment operator for strings in C, enabling you to effectively manipulate and work with strings in your C programs. By using built-in C functions or defining your own custom functions, you can assign strings to character arrays, which allow you to perform various operations on strings, such as concatenation, comparison, substring search, and more.

Assignment Operator in C - Key takeaways

Assignment Operator in C: represented by the equal sign (=), assigns a value to a variable

Compound assignment operators in C: combine arithmetic or bitwise operations with the assignment operator, such as +=, -=, and *=

Addition assignment operator in C: represented by (+=), adds a value to an existing variable and assigns the new value

Assignment operator for string in C : requires specific functions like strcpy() or custom functions, as direct assignment with = is not possible

Assignment Operator in C example: int x = 5; assigns the value 5 to the variable x

Flashcards in Assignment Operator in C 11

What symbol is used as the assignment operator in C programming?

An equal sign (=)

What is the syntax for the addition assignment operator in C?

variable += value;

What is the compound assignment operator for multiplication in C?

Why is direct assignment of a string using the assignment operator (=) not possible in C?

Arrays cannot be assigned using the assignment operator.

How can a string be assigned to a character array using the `strcpy()` function in C?

GetString(destination, source);

Which function or method can be used to assign a string to a character array in C programming?

Using the `strcpy()` function or a custom assignment function.

Assignment Operator in C

Learn with 11 Assignment Operator in C flashcards in the free StudySmarter app

We have 14,000 flashcards about Dynamic Landscapes.

Already have an account? Log in

Frequently Asked Questions about Assignment Operator in C

Test your knowledge with multiple choice flashcards.

Assignment Operator in C

Join the StudySmarter App and learn efficiently with millions of flashcards and more!

Keep learning, you are doing great.

Discover learning materials with the free StudySmarter app

1

About StudySmarter

StudySmarter is a globally recognized educational technology company, offering a holistic learning platform designed for students of all ages and educational levels. Our platform provides learning support for a wide range of subjects, including STEM, Social Sciences, and Languages and also helps students to successfully master various tests and exams worldwide, such as GCSE, A Level, SAT, ACT, Abitur, and more. We offer an extensive library of learning materials, including interactive flashcards, comprehensive textbook solutions, and detailed explanations. The cutting-edge technology and tools we provide help students create their own learning materials. StudySmarter’s content is not only expert-verified but also regularly updated to ensure accuracy and relevance.

Assignment Operator in C

StudySmarter Editorial Team

Team Assignment Operator in C Teachers

  • 10 minutes reading time
  • Checked by StudySmarter Editorial Team

Study anywhere. Anytime.Across all devices.

Create a free account to save this explanation..

Save explanations to your personalised space and access them anytime, anywhere!

By signing up, you agree to the Terms and Conditions and the Privacy Policy of StudySmarter.

Sign up to highlight and take notes. It’s 100% free.

Join over 22 million students in learning with our StudySmarter App

The first learning app that truly has everything you need to ace your exams in one place

  • Flashcards & Quizzes
  • AI Study Assistant
  • Study Planner
  • Smart Note-Taking

Join over 22 million students in learning with our StudySmarter App

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Expressions and operators

This chapter documents all the JavaScript language operators, expressions and keywords.

Expressions and operators by category

For an alphabetical listing see the sidebar on the left.

Primary expressions

Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ).

The this keyword refers to a special property of an execution context.

Basic null , boolean, number, and string literals.

Array initializer/literal syntax.

Object initializer/literal syntax.

The function keyword defines a function expression.

The class keyword defines a class expression.

The function* keyword defines a generator function expression.

The async function defines an async function expression.

The async function* keywords define an async generator function expression.

Regular expression literal syntax.

Template literal syntax.

Grouping operator.

Left-hand-side expressions

Left values are the destination of an assignment.

Member operators provide access to a property or method of an object ( object.property and object["property"] ).

The optional chaining operator returns undefined instead of causing an error if a reference is nullish ( null or undefined ).

The new operator creates an instance of a constructor.

In constructors, new.target refers to the constructor that was invoked by new .

An object exposing context-specific metadata to a JavaScript module.

The super keyword calls the parent constructor or allows accessing properties of the parent object.

The import() syntax allows loading a module asynchronously and dynamically into a potentially non-module environment.

Increment and decrement

Postfix/prefix increment and postfix/prefix decrement operators.

Postfix increment operator.

Postfix decrement operator.

Prefix increment operator.

Prefix decrement operator.

Unary operators

A unary operation is an operation with only one operand.

The delete operator deletes a property from an object.

The void operator evaluates an expression and discards its return value.

The typeof operator determines the type of a given object.

The unary plus operator converts its operand to Number type.

The unary negation operator converts its operand to Number type and then negates it.

Bitwise NOT operator.

Logical NOT operator.

Pause and resume an async function and wait for the promise's fulfillment/rejection.

Arithmetic operators

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

Exponentiation operator.

Multiplication operator.

Division operator.

Remainder operator.

Addition operator.

Subtraction operator.

Relational operators

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

Less than operator.

Greater than operator.

Less than or equal operator.

Greater than or equal operator.

The instanceof operator determines whether an object is an instance of another object.

The in operator determines whether an object has a given property.

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

Equality operators

The result of evaluating an equality operator is always of type boolean based on whether the comparison is true.

Equality operator.

Inequality operator.

Strict equality operator.

Strict inequality operator.

Bitwise shift operators

Operations to shift all bits of the operand.

Bitwise left shift operator.

Bitwise right shift operator.

Bitwise unsigned right shift operator.

Binary bitwise operators

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

Bitwise AND.

Bitwise OR.

Bitwise XOR.

Binary logical operators

Logical operators implement boolean (logical) values and have short-circuiting behavior.

Logical AND.

Logical OR.

Nullish Coalescing Operator.

Conditional (ternary) operator

The conditional operator returns one of two values based on the logical value of the condition.

Assignment operators

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

Assignment operator.

Multiplication assignment.

Division assignment.

Remainder assignment.

Addition assignment.

Subtraction assignment

Left shift assignment.

Right shift assignment.

Unsigned right shift assignment.

Bitwise AND assignment.

Bitwise XOR assignment.

Bitwise OR assignment.

Exponentiation assignment.

Logical AND assignment.

Logical OR assignment.

Nullish coalescing assignment.

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

Yield operators

Pause and resume a generator function.

Delegate to another generator function or iterable object.

Spread syntax

Spread syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.

Comma operator

The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.

Specifications

Specification

Browser compatibility

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

  • Operator precedence

Learn C++ practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c++ interactively, introduction to c++.

  • Getting Started With C++
  • Your First C++ Program
  • C++ Comments

C++ Fundamentals

  • C++ Keywords and Identifiers
  • C++ Variables, Literals and Constants
  • C++ Data Types
  • C++ Type Modifiers
  • C++ Constants
  • C++ Basic Input/Output
  • C++ Operators

Flow Control

C++ Relational and Logical Operators

  • C++ if, if...else and Nested if...else
  • C++ for Loop
  • C++ while and do...while Loop
  • C++ break Statement
  • C++ continue Statement
  • C++ goto Statement
  • C++ switch..case Statement

C++ Ternary Operator

  • C++ Functions
  • C++ Programming Default Arguments
  • C++ Function Overloading
  • C++ Inline Functions
  • C++ Recursion

Arrays and Strings

  • C++ Array to Function
  • C++ Multidimensional Arrays
  • C++ String Class

Pointers and References

  • C++ Pointers
  • C++ Pointers and Arrays
  • C++ References: Using Pointers
  • C++ Call by Reference: Using pointers
  • C++ Memory Management: new and delete

Structures and Enumerations

  • C++ Structures
  • C++ Structure and Function
  • C++ Pointers to Structure
  • C++ Enumeration

Object Oriented Programming

  • C++ Classes and Objects
  • C++ Constructors
  • C++ Constructor Overloading
  • C++ Destructors
  • C++ Access Modifiers
  • C++ Encapsulation
  • C++ friend Function and friend Classes

Inheritance & Polymorphism

  • C++ Inheritance
  • C++ Public, Protected and Private Inheritance
  • C++ Multiple, Multilevel and Hierarchical Inheritance
  • C++ Function Overriding
  • C++ Virtual Functions
  • C++ Abstract Class and Pure Virtual Function

STL - Vector, Queue & Stack

  • C++ Standard Template Library
  • C++ STL Containers
  • C++ std::array
  • C++ Vectors
  • C++ Forward List
  • C++ Priority Queue

STL - Map & Set

  • C++ Multimap
  • C++ Multiset
  • C++ Unordered Map
  • C++ Unordered Set
  • C++ Unordered Multiset
  • C++ Unordered Multimap

STL - Iterators & Algorithms

  • C++ Iterators
  • C++ Algorithm
  • C++ Functor

Additional Topics

  • C++ Exceptions Handling
  • C++ File Handling
  • C++ Ranged for Loop
  • C++ Nested Loop
  • C++ Function Template
  • C++ Class Templates
  • C++ Type Conversion
  • C++ Type Conversion Operators
  • C++ Operator Overloading

Advanced Topics

  • C++ Namespaces
  • C++ Preprocessors and Macros
  • C++ Storage Class

C++ Bitwise Operators

  • C++ Buffers
  • C++ istream
  • C++ ostream

C++ Tutorials

C++ Operator Precedence and Associativity

  • Subtract Complex Number Using Operator Overloading
  • Increment ++ and Decrement -- Operator Overloading in C++ Programming

Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.

Operators in C++ can be classified into 6 types:

  • Arithmetic Operators
  • Assignment Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Other Operators

1. C++ Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For example,

Here, the + operator is used to add two variables a and b . Similarly there are various other arithmetic operators in C++.

Operator Operation
Addition
Subtraction
Multiplication
Division
Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators

Here, the operators + , - and * compute addition, subtraction, and multiplication respectively as we might have expected.

/ Division Operator

Note the operation (a / b) in our program. The / operator is the division operator.

As we can see from the above example, if an integer is divided by another integer, we will get the quotient. However, if either divisor or dividend is a floating-point number, we will get the result in decimals.

% Modulo Operator

The modulo operator % computes the remainder. When a = 9 is divided by b = 4 , the remainder is 1 .

Note: The % operator can only be used with integers.

  • Increment and Decrement Operators

C++ also provides increment and decrement operators: ++ and -- respectively.

  • ++ increases the value of the operand by 1
  • -- decreases it by 1

For example,

Here, the code ++num; increases the value of num by 1 .

Example 2: Increment and Decrement Operators

In the above program, we have used the ++ and -- operators as prefixes (++a and --b) . However, we can also use these operators as postfix (a++ and b--) .

To learn more, visit increment and decrement operators .

2. C++ Assignment Operators

In C++, assignment operators are used to assign values to variables. For example,

Here, we have assigned a value of 5 to the variable a .

Operator Example Equivalent to

Example 3: Assignment Operators

3. c++ relational operators.

A relational operator is used to check the relationship between two operands. For example,

Here, > is a relational operator. It checks if a is greater than b or not.

If the relation is true , it returns 1 whereas if the relation is false , it returns 0 .

Operator Meaning Example
Is Equal To gives us
Not Equal To gives us
Greater Than gives us
Less Than gives us
Greater Than or Equal To give us
Less Than or Equal To gives us

Example 4: Relational Operators

Note : Relational operators are used in decision-making and loops.

4. C++ Logical Operators

Logical operators are used to check whether an expression is true or false . If the expression is true , it returns 1 whereas if the expression is false , it returns 0 .

Operator Example Meaning
expression1 expression2 Logical AND.
True only if all the operands are true.
expression1 expression2 Logical OR.
True if at least one of the operands is true.
expression Logical NOT.
True only if the operand is false.

In C++, logical operators are commonly used in decision making. To further understand the logical operators, let's see the following examples,

Example 5: Logical Operators

Explanation of logical operator program

  • (3 != 5) && (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
  • (3 == 5) && (3 < 5) evaluates to 0 because the operand (3 == 5) is 0 (false).
  • (3 == 5) && (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
  • (3 != 5) || (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
  • (3 != 5) || (3 > 5) evaluates to 1 because the operand (3 != 5) is 1 (true).
  • (3 == 5) || (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
  • !(5 == 2) evaluates to 1 because the operand (5 == 2) is 0 (false).
  • !(5 == 5) evaluates to 0 because the operand (5 == 5) is 1 (true).

5. C++ Bitwise Operators

In C++, bitwise operators are used to perform operations on individual bits. They can only be used alongside char and int data types.

Operator Description
Binary AND
Binary OR
Binary XOR
Binary One's Complement
Binary Shift Left
Binary Shift Right

To learn more, visit C++ bitwise operators .

6. Other C++ Operators

Here's a list of some other common operators available in C++. We will learn about them in later tutorials.

Operator Description Example
returns the size of data type
returns value based on the condition
represents memory address of the operand
accesses members of struct variables or class objects
used with pointers to access the class or struct variables
prints the output value
gets the input value
  • C++ Operators Precedence and Associativity

Table of Contents

Sorry about that.

Related Tutorials

C++ Tutorial

U.S. flag

Official websites use .gov

A .gov website belongs to an official government organization in the United States.

Secure .gov websites use HTTPS

A lock ( ) or https:// means you've safely connected to the .gov website. Share sensitive information only on official, secure websites.

CDC Current Outbreak List

Infectious disease outbreaks currently being reported on by CDC. Listings include those outbreaks for which content is currently published on the CDC website.

Recent investigations reported on CDC.gov

  • Cucumbers – Salmonella Outbreak Announced June 2024
  • Backyard Poultry – Salmonella Outbreaks Announced May 2024
  • Organic Walnuts – E coli Outbreak Announced April 2024
  • Fresh Basil – Salmonella Outbreak Announced April 2024
  • Measles Outbreaks 2024 Announced January 2024
  • Coronavirus Disease 2019 (COVID-19) Announced January 2020

Please see the Travelers’ Health site for a complete list.

In the last two years, CDC has sent scientists and doctors out more than 750 times to respond to health threats. Learn more below.

  • Investigating Foodborne Outbreaks
  • Waterborne Outbreaks Toolkit
  • Ebola Outbreak History Announced September 2022
  • Mpox Outbreaks Announced May 2022
  • Multistate Foodborne Outbreaks – Foodborne outbreaks listed by year
  • Hepatitis A Outbreaks – Hepatitis A outbreak investigations since 2013 where CDC supported or led the investigation.
  • US Outbreaks Linked to Contact with Animals or Animal Products
  • Health Alert Network – Health alerts, health advisories, updates, and info service messages. Designed for public health and medical communities.
  • Recent Outbreaks and Incidents – Events involving the CDC Emergency Operations Center
  • Morbidity and Mortality Weekly Report – Outbreak investigation reports included among other content. Note that outbreak material includes state health department investigations. Designed for public health and medical communities.

Exit Notification / Disclaimer Policy

  • The Centers for Disease Control and Prevention (CDC) cannot attest to the accuracy of a non-federal website.
  • Linking to a non-federal website does not constitute an endorsement by CDC or any of its employees of the sponsors or the information and products presented on the website.
  • You will be subject to the destination website's privacy policy when you follow the link.
  • CDC is not responsible for Section 508 compliance (accessibility) on other federal or private website.
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

OperatorDescriptionSyntax
+Addition: adds two operandsx + y
Subtraction: subtracts two operandsx – y
*Multiplication: multiplies two operandsx * y
/Division (float): divides the first operand by the secondx / y
//Division (floor): divides the first operand by the secondx // y
%Modulus: returns the remainder when the first operand is divided by the secondx % y
**Power: Returns first raised to power secondx ** y

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

OperatorDescriptionSyntax
>Greater than: True if the left operand is greater than the rightx > y
<Less than: True if the left operand is less than the rightx < y
==Equal to: True if both operands are equalx == y
!=Not equal to – True if operands are not equalx != y
>=Greater than or equal to True if the left operand is greater than or equal to the rightx >= y
<=Less than or equal to True if the left operand is less than or equal to the rightx <= y

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

OperatorDescriptionSyntax
andLogical AND: True if both the operands are truex and y
orLogical OR: True if either of the operands is true x or y
notLogical NOT: True if the operand is false not x

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

OperatorDescriptionSyntax
&Bitwise ANDx & y
|Bitwise ORx | y
~Bitwise NOT~x
^Bitwise XORx ^ y
>>Bitwise right shiftx>>
<<Bitwise left shiftx<<

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

OperatorDescriptionSyntax
=Assign the value of the right side of the expression to the left side operand x = y + z
+=Add AND: Add right-side operand with left-side operand and then assign to left operanda+=b     a=a+b
-=Subtract AND: Subtract right operand from left operand and then assign to left operanda-=b     a=a-b
*=Multiply AND: Multiply right operand with left operand and then assign to left operanda*=b     a=a*b
/=Divide AND: Divide left operand with right operand and then assign to left operanda/=b     a=a/b
%=Modulus AND: Takes modulus using left and right operands and assign the result to left operanda%=b     a=a%b
//=Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operanda//=b     a=a//b
**=Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operanda**=b     a=a**b
&=Performs Bitwise AND on operands and assign value to left operanda&=b     a=a&b
|=Performs Bitwise OR on operands and assign value to left operanda|=b     a=a|b
^=Performs Bitwise xOR on operands and assign value to left operanda^=b     a=a^b
>>=Performs Bitwise right shift on operands and assign value to left operanda>>=b     a=a>>b
<<=Performs Bitwise left shift on operands and assign value to left operanda <<= b     a= a << b

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Assignment Operators

    compound assignment operators in c with example

  2. Compound Assignment Operators in C Programming Language

    compound assignment operators in c with example

  3. 025 Compound assignment operators (Welcome to the course C programming)

    compound assignment operators in c with example

  4. Assignment Operators in C Detailed Explanation

    compound assignment operators in c with example

  5. PPT

    compound assignment operators in c with example

  6. C++ Compound Assignment Operators

    compound assignment operators in c with example

VIDEO

  1. Assignment Operator in C Programming

  2. ICs Computer Part 2, Ch 9

  3. C BASICS IN COMPETITIVE EXAMS (PART-1) || COMMA AS AN OPERATOR IN C || COMMA AS AN SEPARATOR IN C

  4. Assignment Operator in C Programming

  5. Operators in C language

  6. Assignment Operators

COMMENTS

  1. C Compound Assignment

    The result of a compound-assignment operation has the value and type of the left operand. #define MASK 0xff00 n &= MASK; In this example, a bitwise-inclusive-AND operation is performed on n and MASK, and the result is assigned to n. The manifest constant MASK is defined with a #define preprocessor directive. See also. C Assignment Operators

  2. Assignment Operators in C

    Different types of assignment operators are shown below: 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 ...

  3. Assignment Operators in C

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

  4. Assignment Operators In C [ Full Information With Examples ]

    Examples of compound assignment operators are: (Example: + =, - =, * =, / =,% =, & =, ^ =) Look at these two statements: x = 100; x = x + 5; Here in this example, adding 5 to the x variable in the second statement is again being assigned to the x variable. Compound Assignment Operators provide us with the C language to perform such operation ...

  5. Assignment and shorthand assignment operator in C

    C supports a short variant of assignment operator called compound assignment or shorthand assignment. Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator. For example, consider following C statements. The above expression a = a + 2 is equivalent to a += 2.

  6. Assignment operators

    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: a becomes equal to b: ... In C++, assignment operators are lvalue expressions, not so in C.

  7. C

    A special case scenario for all the compound assigned operators. int i= 2 ; i+= 2 * 2 ; //equals to, i = i+(2*2); In all the compound assignment operators, the expression on the right side of = is always calculated first and then the compound assignment operator will start its functioning. Hence in the last code, statement i+=2*2; is equal to i ...

  8. Assignment Operator in C: Compound, Addition, Example

    Here are some more examples of using the assignment operator in C: int a = 10; // Declare and assign in a single line float b = 3.14; char c = 'A'; Additionally, you can use the assignment operator with various arithmetic, relational, and logical operators: `+=`: Add and assign. `-=`: Subtract and assign.

  9. C Assignment Operators

    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 (+=): int x = 5; x += 10; Code language: C++ (cpp) The ...

  10. C Programming Assignment Operators

    Assignment Operators in C are used to assign values to the variables. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=". In this C tutorial, we'll understand the types of C programming assignment operators with examples.

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

  12. Compound Assignment Operators in C

    What your ancient compiler is doing is correctly following the C grammar rules and is grouping the expression as. a += (a += (a += 2)) But grouping is not the same as sequencing. From this point the behaviour is undefined. Your compiler appears to evaluate the above to. a += (a += 7) followed by. a += 14.

  13. What is the difference between += and =+ C assignment operators

    20. In modern C, or even moderately ancient C, += is a compound assignment operator, and =+ is parsed as two separate tokens. = and +. Punctuation tokens are allowed to be adjacent. So if you write: x += y; it's equivalent to. x = x + y; except that x is only evaluated once (which can matter if it's a more complicated expression).

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

  15. Compound assignment operators

    The compound assignment operators consist of a binary operator and the simple assignment operator. They perform the operation of the binary operator on both operands and store the result of that operation into the left operand, which must be a modifiable lvalue. The following table shows the operand types of compound assignment expressions:

  16. 1.5. Compound Assignment Operators

    1.5. Compound Assignment Operators¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x.It is the same as x = x + 1.This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound ...

  17. Assignment Operators In C++

    In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way. Syntax. variable += value; This above expression is equivalent to the expression: variable = variable + value; Example.

  18. Operators

    Compound assignment operators modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand: ... Two expressions can be compared using relational and equality operators. For example, to know if two values are equal or if one is greater than the other ...

  19. Compound Assignment Operators in C++

    The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −. The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once. The following are the compound assignment operators in C++ −. Multiply the value of the first operand by the ...

  20. Compound Assignment Operator in C with Example

    In this video we are going to study about.. Assignment Operator in C Assignment Operator Example Use of Assignment Operator in CCompound Assignment Operato...

  21. Operators in C and C++

    This is a list of operators in the C and C++ programming languages.All the operators (except typeof) listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.. When not overloaded, for the operators &&, ||, and , (the comma operator), there is a sequence point after the evaluation of the first operand.

  22. Assignment Operator in C: Compound, Addition, Example

    Here are some more examples of using the assignment operator in C: int a = 10; // Declare and assign in a single line float b = 3.14; char c = 'A'; Additionally, you can use the assignment operator with various arithmetic, relational, and logical operators: `+=`: Add and assign. `-=`: Subtract and assign.

  23. Expressions and operators

    Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ). The this keyword refers to a special property of an execution context. Basic null, boolean, number, and string literals. Array initializer/literal syntax. Object initializer/literal syntax.

  24. C++ Operators

    C++ Operators. Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction. Operators in C++ can be classified into 6 types: Arithmetic Operators. Assignment Operators.

  25. CDC Current Outbreak List

    Level 1 - Oropouche Fever in the Americas June 2024. Level 2 - Chikungunya in Maldives May 2024. Level 1 - Global Measles May 2024. Level 2 - Global Polio May 2024. Level 1 - Meningococcal Disease in Saudi Arabia - Vaccine Requirements for Travel During the Hajj and Umrah Pilgrimages May 2024.

  26. Python Operators

    Assignment Operators in Python. Let's see an example of Assignment Operators in Python. Example: The code starts with 'a' and 'b' both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on 'b'.