CProgramming Tutorial

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

Assignment Operators in C

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

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

Simple assignment operator (=)

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

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

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

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

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

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

Augmented assignment operators

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

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

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

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

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

Learn C practically and Get Certified .

Popular Tutorials

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

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples

Bitwise Operators in C Programming

C Precedence And Associativity Of Operators

  • Compute Quotient and Remainder
  • Find the Size of int, float, double and char

C if...else Statement

  • Demonstrate the Working of Keyword long

C Programming Operators

An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.

C has a wide range of operators to perform various operations.

C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).

Example 1: Arithmetic Operators

The operators + , - and * computes addition, subtraction, and multiplication respectively as you might have expected.

In normal calculation, 9/4 = 2.25 . However, the output is 2 in the program.

It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25 .

The modulo operator % computes the remainder. When a=9 is divided by b=4 , the remainder is 1 . The % operator can only be used with integers.

Suppose a = 5.0 , b = 2.0 , c = 5 and d = 2 . Then in C programming,

C Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.

Example 2: Increment and Decrement Operators

Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes like a++ and a-- . Visit this page to learn more about how increment and decrement operators work when used as postfix .

C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment operator is =

Example 3: Assignment Operators

C relational operators.

A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops .

Example 4: Relational Operators

C logical operators.

An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming .

Example 5: Logical Operators

Explanation of logical operator program

  • (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
  • (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
  • (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
  • (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
  • !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
  • !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Visit bitwise operator in C to learn more.

Other Operators

Comma operator.

Comma operators are used to link related expressions together. For example:

The sizeof operator

The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).

Example 6: sizeof Operator

Other operators such as ternary operator ?: , reference operator & , dereference operator * and member selection operator  ->  will be discussed in later tutorials.

Table of Contents

  • Arithmetic Operators
  • Increment and Decrement Operators
  • Assignment Operators
  • Relational Operators
  • Logical Operators
  • sizeof Operator

Video: Arithmetic Operators in C

Sorry about that.

Related Tutorials

MarketSplash

Mastering The Art Of Assignment: Exploring C Assignment Operators

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

💡 KEY INSIGHTS

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

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

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

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

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

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

The Basics Of C Operators

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

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

What Are Operators In C?

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

Categories Of Operators In C

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

Let's break it down:

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

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

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

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

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

What Are Assignment Operators?

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

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

Syntax And Usage Of Assignment Operators

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

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

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

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

List Of Assignment Operators In C

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

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

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

The Simple Assignment Operator '='

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

Take a look at this:

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

The Addition Assignment Operator '+='

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

Consider this:

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

The Subtraction Assignment Operator '-='

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

For instance:

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

The Multiplication Assignment Operator '*='

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

Check this out:

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

The Division Assignment Operator '/='

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

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

The Modulus Assignment Operator '%='

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

Look at this:

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

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

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

Variable Initialization And Value Change

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

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

Calculation Updates In Real-Time Applications

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

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

Running Totals And Averages

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

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

Iterations In Loop Constructs

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

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

Working With Remainders

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

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

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

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

Confusing Assignment With Equality

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

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

Overlooking Operator Precedence

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

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

Misusing Modulo With Floats

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

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

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

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

Exercise 1: The Shy Variable

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

Exercise 2: Sneaky Increment

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

Exercise 3: Modulo Madness

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

Exercise 4: Swapping Values

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

Exercise 5: Converting Fahrenheit To Celsius

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

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

References and Further Reading

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

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

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

2. Expert C Programming by Peter van der Linden

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

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

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

4. The Pragmatic Programmer by Andrew Hunt and David Thomas

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

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

6. Cprogramming.com

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

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

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

Which C assignment operator adds a value to a variable?

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

Continue Learning With These C Guides

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

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

Home » Learn C Programming from Scratch » C Assignment Operators

C Assignment Operators

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

Introduction to the C assignment operators

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

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

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

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

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

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

The expression:

is equivalent to the following expression:

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

  • A simple assignment operator assigns the value of the left operand to the right operand.
  • A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

This browser is no longer supported.

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

Assignment operators

  • 8 contributors

expression assignment-operator expression

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

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

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

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

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

Assignment operators table

Operator keywords.

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

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

Simple assignment

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

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

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

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

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

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

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

the assignment statement

can have one of the following effects:

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

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

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

Compound assignment

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

an arithmetic type

a pointer, if op is + or -

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

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

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

Result of built-in assignment operators

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

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

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

Was this page helpful?

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

Submit and view feedback for

Additional resources

cppreference.com

C operator precedence.

The following table lists the precedence and associativity of C operators. Operators are listed top to bottom, in descending precedence.

  • ↑ The operand of prefix ++ and -- can't be a type cast. This rule grammatically forbids some expressions that would be semantically invalid anyway. Some compilers ignore this rule and detect the invalidity semantically.
  • ↑ The operand of sizeof can't be a type cast: the expression sizeof ( int ) * p is unambiguously interpreted as ( sizeof ( int ) ) * p , but not sizeof ( ( int ) * p ) .
  • ↑ The expression in the middle of the conditional operator (between ? and : ) is parsed as if parenthesized: its precedence relative to ?: is ignored.
  • ↑ Assignment operators' left operands must be unary (level-2 non-cast) expressions. This rule grammatically forbids some expressions that would be semantically invalid anyway. Many compilers ignore this rule and detect the invalidity semantically. For example, e = a < d ? a ++ : a = d is an expression that cannot be parsed because of this rule. However, many compilers ignore this rule and parse it as e = ( ( ( a < d ) ? ( a ++ ) : a ) = d ) , and then give an error because it is semantically invalid.

When parsing an expression, an operator which is listed on some row will be bound tighter (as if by parentheses) to its arguments than any operator that is listed on a row further below it. For example, the expression * p ++ is parsed as * ( p ++ ) , and not as ( * p ) ++ .

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. For example, the expression a = b = c is parsed as a = ( b = c ) , and not as ( a = b ) = c because of right-to-left associativity.

[ edit ] Notes

Precedence and associativity are independent from order of evaluation .

The standard itself doesn't specify precedence levels. They are derived from the grammar.

In C++, the conditional operator has the same precedence as assignment operators, and prefix ++ and -- and assignment operators don't have the restrictions about their operands.

Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always associate right-to-left ( sizeof ++* p is sizeof ( ++ ( * p ) ) ) and unary postfix operators always associate left-to-right ( a [ 1 ] [ 2 ] ++ is ( ( a [ 1 ] ) [ 2 ] ) ++ ). Note that the associativity is meaningful for member access operators, even though they are grouped with unary postfix operators: a. b ++ is parsed ( a. b ) ++ and not a. ( b ++ ) .

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • A.2.1 Expressions
  • C11 standard (ISO/IEC 9899:2011):
  • C99 standard (ISO/IEC 9899:1999):
  • C89/C90 standard (ISO/IEC 9899:1990):
  • A.1.2.1 Expressions

[ edit ] See also

Order of evaluation of operator arguments at run time.

  • 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 31 July 2023, at 09:28.
  • This page has been accessed 2,665,989 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

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

Programming

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

Web & Server

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

C++ Multiplication Assignment (*=) Operator

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

C++ Multiplication Assignment

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

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

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

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

Popular Courses by TutorialKart

App developement, web development, online tools.

Assignment Operators in C

C++ Course: Learn the Essentials

Operators are a fundamental part of all the computations that computers perform. Today we will learn about one of them known as Assignment Operators in C. Assignment Operators are used to assign values to variables. The most common assignment operator is = . Assignment Operators are Binary Operators.

Types of Assignment Operators in C

LHS and RHS Operands

Here is a list of the assignment operators that you can find in the C language:

  • basic assignment ( = )
  • subtraction assignment ( -= )
  • addition assignment ( += )
  • division assignment ( /= )
  • multiplication assignment ( *= )
  • modulo assignment ( %= )
  • bitwise XOR assignment ( ^= )
  • bitwise OR assignment ( |= )
  • bitwise AND assignment ( &= )
  • bitwise right shift assignment ( >>= )
  • bitwise left shift assignment ( <<= )

Working of Assignment Operators in C

This is the complete list of all assignment operators in C. To read the meaning of operator please keep in mind the above example.

Example for Assignment Operators in C

Basic assignment ( = ) :

Subtraction assignment ( -= ) :

Addition assignment ( += ) :

Division assignment ( /= ) :

Multiplication assignment ( *= ) :

Modulo assignment ( %= ) :

Bitwise XOR assignment ( ^= ) :

Bitwise OR assignment ( |= ) :

Bitwise AND assignment ( &= ) :

Bitwise right shift assignment ( >>= ) :

Bitwise left shift assignment ( <<= ) :

This is the detailed explanation of all the assignment operators in C that we have. Hopefully, This is clear to you.

Practice Problems on Assignment Operators in C

1. what will be the value of a after the following code is executed.

A) 10 B) 11 C) 12 D) 15

Answer – C. 12 Explanation: a starts at 10, increases by 5 to 15, then decreases by 3 to 12. So, a is 12.

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

A) 4 B) 8 C) 16 D) 32

Answer: C) 16 Explanation: After right-shifting 8 (binary 1000) by one and then left-shifting the result by two, the value becomes 16 (binary 10000).

Q. How does the /= operator function? Is it a combination of two other operators?

A. The /= operator is a compound assignment operator in C++. It divides the left operand by the right operand and assigns the result to the left operand. It is equivalent to using the / operator and then the = operator separately.

Q. What is the most basic operator among all the assignment operators available in the C language?

A. The most basic assignment operator in the C language is the simple = operator, which is used for assigning a value to a variable.

  • Assignment operators are used to assign the result of an expression to a variable.
  • There are two types of assignment operators in C. Simple assignment operator and compound assignment operator.
  • Compound Assignment operators are easy to use and the left operand of expression needs not to write again and again.
  • They work the same way in C++ as in C.
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • Solve Coding Problems
  • Bitmask in C++
  • C++ Variable Templates
  • vTable And vPtr in C++
  • Address Operator & in C
  • Macros In C++
  • Variable Shadowing in C++
  • Unique_ptr in C++
  • Pass By Reference In C
  • C++ Program For Sentinel Linear Search
  • Partial Template Specialization in C++
  • Difference Between Constant and Literals
  • Concurrency in C++
  • String Tokenization in C
  • Decision Making in C++
  • auto_ptr in C++
  • shared_ptr in C++
  • Mutex in C++
  • C++ 20 - <semaphore> Header
  • Compound Statements in C++

Assignment Operators In C++

In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other words, it is used to store some kind of information.

The right-hand side value will be assigned to the variable on the left-hand side. The variable and the value should be of the same data type.

The value can be a literal or another variable of the same data type.

Compound Assignment Operators

In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. There are 10 compound assignment operators in C++:

  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )
  • Bitwise AND Assignment Operator ( &= )
  • Bitwise OR Assignment Operator ( |= )
  • Bitwise XOR Assignment Operator ( ^= )
  • Left Shift Assignment Operator ( <<= )
  • Right Shift Assignment Operator ( >>= )

Lets see each of them in detail.

1. Addition Assignment Operator (+=)

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.

This above expression is equivalent to the expression:

2. Subtraction Assignment Operator (-=)

The subtraction assignment operator (-=) in C++ enables you to update the value of the variable by subtracting another value from it. This operator is especially useful when you need to perform subtraction and store the result back in the same variable.

3. Multiplication Assignment Operator (*=)

In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another value.

4. Division Assignment Operator (/=)

The division assignment operator divides the variable on the left by the value on the right and assigns the result to the variable on the left.

5. Modulus Assignment Operator (%=)

The modulus assignment operator calculates the remainder when the variable on the left is divided by the value or variable on the right and assigns the result to the variable on the left.

6. Bitwise AND Assignment Operator (&=)

This operator performs a bitwise AND between the variable on the left and the value on the right and assigns the result to the variable on the left.

7. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator performs a bitwise OR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

8. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator performs a bitwise XOR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

9. Left Shift Assignment Operator (<<=)

The left shift assignment operator shifts the bits of the variable on the left to left by the number of positions specified on the right and assigns the result to the variable on the left.

10. Right Shift Assignment Operator (>>=)

The right shift assignment operator shifts the bits of the variable on the left to the right by a number of positions specified on the right and assigns the result to the variable on the left.

Also, it is important to note that all of the above operators can be overloaded for custom operations with user-defined data types to perform the operations we want.

Please Login to comment...

  • Geeks Premier League 2023
  • Geeks Premier League
  • 10 Best Chegg Alternatives in 2024
  • Devin AI: World’s First AI Software Engineer
  • 12 Best FlexClip Alternatives & Competitors in 2024 [Free + Paid]
  • What Is Trunk-Or-Treat?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Assignment operator in c.

' src=

Last Updated on June 23, 2023 by Prepbytes

multiplying assignment operator c

This type of operator is employed for transforming and assigning values to variables within an operation. In an assignment operation, the right side represents a value, while the left side corresponds to a variable. It is essential that the value on the right side has the same data type as the variable on the left side. If this requirement is not fulfilled, the compiler will issue an error.

What is Assignment Operator in C language?

In C, the assignment operator serves the purpose of assigning a value to a variable. It is denoted by the equals sign (=) and plays a vital role in storing data within variables for further utilization in code. When using the assignment operator, the value present on the right-hand side is assigned to the variable on the left-hand side. This fundamental operation allows developers to store and manipulate data effectively throughout their programs.

Example of Assignment Operator in C

For example, consider the following line of code:

Types of Assignment Operators in C

Here is a list of the assignment operators that you can find in the C language:

Simple assignment operator (=): This is the basic assignment operator, which assigns the value on the right-hand side to the variable on the left-hand side.

Addition assignment operator (+=): This operator adds the value on the right-hand side to the variable on the left-hand side and assigns the result back to the variable.

x += 3; // Equivalent to x = x + 3; (adds 3 to the current value of "x" and assigns the result back to "x")

Subtraction assignment operator (-=): This operator subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result back to the variable.

x -= 4; // Equivalent to x = x – 4; (subtracts 4 from the current value of "x" and assigns the result back to "x")

* Multiplication assignment operator ( =):** This operator multiplies the value on the right-hand side with the variable on the left-hand side and assigns the result back to the variable.

x = 2; // Equivalent to x = x 2; (multiplies the current value of "x" by 2 and assigns the result back to "x")

Division assignment operator (/=): This operator divides the variable on the left-hand side by the value on the right-hand side and assigns the result back to the variable.

x /= 2; // Equivalent to x = x / 2; (divides the current value of "x" by 2 and assigns the result back to "x")

Bitwise AND assignment (&=): The bitwise AND assignment operator "&=" performs a bitwise AND operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x &= 3; // Binary: 0011 // After bitwise AND assignment: x = 1 (Binary: 0001)

Bitwise OR assignment (|=): The bitwise OR assignment operator "|=" performs a bitwise OR operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x |= 3; // Binary: 0011 // After bitwise OR assignment: x = 7 (Binary: 0111)

Bitwise XOR assignment (^=): The bitwise XOR assignment operator "^=" performs a bitwise XOR operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x ^= 3; // Binary: 0011 // After bitwise XOR assignment: x = 6 (Binary: 0110)

Left shift assignment (<<=): The left shift assignment operator "<<=" shifts the bits of the value on the left-hand side to the left by the number of positions specified by the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x <<= 2; // Binary: 010100 (Shifted left by 2 positions) // After left shift assignment: x = 20 (Binary: 10100)

Right shift assignment (>>=): The right shift assignment operator ">>=" shifts the bits of the value on the left-hand side to the right by the number of positions specified by the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x >>= 2; // Binary: 101 (Shifted right by 2 positions) // After right shift assignment: x = 5 (Binary: 101)

Conclusion The assignment operator in C, denoted by the equals sign (=), is used to assign a value to a variable. It is a fundamental operation that allows programmers to store data in variables for further use in their code. In addition to the simple assignment operator, C provides compound assignment operators that combine arithmetic or bitwise operations with assignment, allowing for concise and efficient code.

FAQs related to Assignment Operator in C

Q1. Can I assign a value of one data type to a variable of another data type? In most cases, assigning a value of one data type to a variable of another data type will result in a warning or error from the compiler. It is generally recommended to assign values of compatible data types to variables.

Q2. What is the difference between the assignment operator (=) and the comparison operator (==)? The assignment operator (=) is used to assign a value to a variable, while the comparison operator (==) is used to check if two values are equal. It is important not to confuse these two operators.

Q3. Can I use multiple assignment operators in a single statement? No, it is not possible to use multiple assignment operators in a single statement. Each assignment operator should be used separately for assigning values to different variables.

Q4. Are there any limitations on the right-hand side value of the assignment operator? The right-hand side value of the assignment operator should be compatible with the data type of the left-hand side variable. If the data types are not compatible, it may lead to unexpected behavior or compiler errors.

Q5. Can I assign the result of an expression to a variable using the assignment operator? Yes, it is possible to assign the result of an expression to a variable using the assignment operator. For example, x = y + z; assigns the sum of y and z to the variable x.

Q6. What happens if I assign a value to an uninitialized variable? Assigning a value to an uninitialized variable will initialize it with the assigned value. However, it is considered good practice to explicitly initialize variables before using them to avoid potential bugs or unintended behavior.

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.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Null character in c, ackermann function in c, median of two sorted arrays of different size in c, number is palindrome or not in c, implementation of queue using linked list in c, c program to replace a substring in a string.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.

Similarly, you can destructure objects on the left-hand side of the assignment.

This capability is similar to features present in languages such as Perl and Python.

For features specific to array or object destructuring, refer to the individual examples below.

Binding and assignment

For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.

In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.

All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .

In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:

  • The looping variable of for...in for...of , and for await...of loops;
  • Function parameters;
  • The catch binding variable.

In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .

If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.

Note that the equivalent binding pattern of the code above is not valid syntax:

You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .

Default value

Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .

The default value can be any expression. It will only be evaluated when necessary.

Rest property

You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.

The rest property must be the last in the pattern, and must not have a trailing comma.

Array destructuring

Basic variable assignment, destructuring with more elements than the source.

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.

These binding patterns can even be nested, as long as each rest property is the last in the list.

On the other hand, object destructuring can only have an identifier as the rest property.

Unpacking values from a regular expression match

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Using array destructuring on any iterable

Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.

Non-iterables cannot be destructured as arrays.

Iterables are only iterated until all bindings are assigned.

The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.

Object destructuring

Basic assignment, assigning to new variable names.

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .

Assigning to new variable names and providing default values

A property can be both

  • Unpacked from an object and assigned to a variable with a different name.
  • Assigned a default value in case the unpacked value is undefined .

Unpacking properties from objects passed as a function parameter

Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.

Consider this object, which contains information about a user.

Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.

You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.

Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .

Setting a function parameter's default value

Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.

Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.

In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .

You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.

For more information, see Default parameters > Destructured parameter with default value assignment .

Nested object and array destructuring

For of iteration and destructuring, computed object property names and destructuring.

Computed property names, like on object literals , can be used with destructuring.

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.

Destructuring primitive values

Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.

Same as accessing properties, destructuring null or undefined throws a TypeError .

This happens even when the pattern is empty.

Combined array and object destructuring

Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

The prototype chain is looked up when the object is deconstructed

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

Specifications

Browser compatibility.

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

  • Assignment operators
  • ES6 in Depth: Destructuring on hacks.mozilla.org (2015)

IMAGES

  1. Assignment Operators in C » PREP INSTA

    multiplying assignment operator c

  2. Assignment Operators in C

    multiplying assignment operator c

  3. PPT

    multiplying assignment operator c

  4. [100% Working Code]

    multiplying assignment operator c

  5. C programming +=

    multiplying assignment operator c

  6. Assignment Operators in C Programming

    multiplying assignment operator c

VIDEO

  1. Application Assignment

  2. Multiplying By 1 (Intro)

  3. Check if a student passed or failed using turnary operator

  4. swap two numbers using bitwise operator

  5. Decrement Operator In C Complete Explanation #decrementOperatorInC

  6. [Math in my world 5] Unit 11: MULTIPLYING & DIVIDING FRACTIONS

COMMENTS

  1. Assignment operators

    Assignment operators C [edit] C language [edit] Expressions [edit] Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right. Simple assignment The simple assignment operator expressions have the form where

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

  3. Assignment Operators in C

    Simple assignment operator (=) The = operator is the most frequently used operator in C. As per ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed.

  4. Assignment Operators in C

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

  5. C Assignment Operators

    = *= /= %= += -= <<= >>= &= ^= |= The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators: Expand table

  6. Operators in C

    C has a wide range of operators to perform various operations. C Arithmetic Operators An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables). Example 1: Arithmetic Operators // Working of arithmetic operators #include <stdio.h> int main() {

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

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

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

  9. C

    Published Jun 10, 2022. Contribute to Docs. Operators are used to perform operations on variables and values. They are symbols that tell the compiler to perform specific mathematical or logical functions. The C language provides the following types of operators: Arithmetic Operators. Relational Operators.

  10. C Multiplicative Operators

    The multiplication operator causes its two operands to be multiplied. / The division operator causes the first operand to be divided by the second. If two integer operands are divided and the result isn't an integer, it's truncated according to the following rules: - The result of division by 0 is undefined according to the ANSI C standard.

  11. c

    10 Answers Sorted by: 63 Remember that assignment is done right to left, and that they are normal expressions. So from the compilers perspective the line sample1 = sample2 = 0; is the same as sample1 = (sample2 = 0); which is the same as sample2 = 0;

  12. Learn C: Operators Cheatsheet

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

  13. Assignment operators

    The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.

  14. C Operator Precedence

    C Operator Precedence [edit] [edit] [edit] The following table lists the precedence and associativity of C operators. Operators are listed top to bottom, in descending precedence. ↑ The operand of prefix ++ and -- can't be a type cast. This rule grammatically forbids some expressions that would be semantically invalid anyway.

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

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

  16. Assignment Operators in C

    A) 4 B) 8 C) 16 D) 32. Answer: C) 16 Explanation: After right-shifting 8 (binary 1000) by one and then left-shifting the result by two, the value becomes 16 (binary 10000). FAQs. Q. How does the /= operator function? Is it a combination of two other operators? A. The /= operator is a compound assignment operator in C++. It divides the left operand by the right operand and assigns the result to ...

  17. Assignment Operators In C++

    There are 10 compound assignment operators in C++: Addition Assignment Operator ( += ) Subtraction Assignment Operator ( -= ) Multiplication Assignment Operator ( *= ) Division Assignment Operator ( /= ) Modulus Assignment Operator ( %= ) Bitwise AND Assignment Operator ( &= ) Bitwise OR Assignment Operator ( |= )

  18. Assignment Operator in C

    Here is a list of the assignment operators that you can find in the C language: Simple assignment operator (=): This is the basic assignment operator, which assigns the value on the right-hand side to the variable on the left-hand side. Example: int x = 10; // Assigns the value 10 to the variable "x". Addition assignment operator (+=): This ...

  19. c++ compound assignment when multiplying

    1 Is there a way of using the compound assignment operator to achieve something like this: a = (a * 10) + b; Initially I tried the following: a *= 10 + b; but this is equivalent to: a = a * (10 + b) Just curious. Ran across this today. This is not homework. c++ Share Improve this question Follow asked Dec 15, 2011 at 19:59 Cole W 15.2k 6 53 86 3

  20. Assignment Operators

    Code Examples Example 1: Basic Assignment Operator ( =) #include <iostream> int main() { int a; a = 5; std::cout << "The value of a is " << a << std::endl; return 0; } Example 2: Add and Assign ( +=) #include <iostream> int main() { int a = 5; a += 3; // equivalent to a = a + 3 std::cout << "The value of a is " << a << std::endl; return 0; }

  21. Destructuring assignment

    Unpacking values from a regular expression match. When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if ...

  22. operators

    -1 This question already has answers here : What are sequence points, and how do they relate to undefined behavior? (6 answers) Closed 10 years ago. Why do we get different results for the two follow statements: int x = 5; x = x * x++; the output is 26; whereas the next example returns 30, though they are same?! int x = 5; x *= x++; Thank you c++