Library homepage

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

selected template will load here

This action is not available.

Engineering LibreTexts

3.5: Assignment Operator

  • Last updated
  • Save as PDF
  • Page ID 11248

  • Kenneth Leroy Busbee
  • Houston Community College via OpenStax CNX

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

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

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

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

Definitions

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.

Welcome! This site is currently in beta. Get 10% off everything with promo code BETA10.

Python Assignment Operator

  • Introduction

Chained Assignment

Shorthand assignment, shorthand assignment operators, playground: assignment operator practice, assignment methods.

All assignment operators are used to assign values to variables. Wait, is there more than one assignment operator? Yes, but they're all quite similar to the ones you've seen. You've used the most common assignment operator, and its symbol is a single equals sign ( = ).

For example, to assign x the value of 10 you type the following:

Different Assignment Methods

You have used this assignment statement before to assign values to variables. Apart from this very common way of using it, a few other situations use the same symbol for slightly different assignments.

You can assign the same value to multiple variables in one swoop by using an assignment chain:

This construct assigns 10 to x , y , and z . Using the chained assignment statement in Python is rare, but if you see it around, now you know what that's about.

Shorthand assignments, on the other hand, are a common occurrence in Python code. This is where the other assignment operators come into play. Shorthand assignments make writing code more efficient and can improve readability---at least once you know about them!

For example, think of a situation where you have a variable x and you want to add 1 to that variable:

This works well and is perfectly fine Python code. However, there is a more concise way of writing the same code using shorthand assignment :

Check out how the second line in these two code snippets is different. You don't need to write the name of the variable x a second time using the shorthand operator += like in the example above.

Both code examples shown achieve the exact same result and are equivalent. The shorthand assignment allows you to use less code to complete the task.

Python comes with a couple of shorthand assignment operators. Some of the most common ones include the following:

These operators are combinations of familiar arithmetic operators with the assignment operator ( = ). You have already used some of Python's arithmetic operators, and you'll learn more about them in the upcoming lesson.

Play around and combine different operators you can think of with the assignment operator below.

  • Which ones work and do what you expect them to?
  • Which ones don't?

Summary: Python Assignment Operator

  • Assignment operators are used to assign values to variables
  • Shorthand assignment is the most commonly used in Python
  • The table summarizing the assignment operators is provided in the lesson
  • Chain Assignment : A method used to assign multiple variables at one
  • Shorthand Assignment : A series of short forms for manipulating data

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

' src=

Last Updated on June 8, 2023 by Prepbytes

highlight the assignment operator (symbol) in the following code

To fully comprehend the assignment operators in Python, it is important to have a basic understanding of what operators are. Operators are utilized to carry out a variety of operations, including mathematical, bitwise, and logical operations, among others, by connecting operands. Operands are the values that are acted upon by operators. In Python, the assignment operator is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is the most commonly used operator in Python. In this article, we will explore the assignment operator in Python, how it works, and its different types.

What is an Assignment Operator in Python?

The assignment operator in Python is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is used to assign a value to a variable. When an assignment operator is used, the value on the right-hand side is assigned to the variable on the left-hand side. This is a fundamental operation in programming, as it allows developers to store data in variables that can be used throughout their code.

For example, consider the following line of code:

Explanation: In this case, the value 10 is assigned to the variable a using the assignment operator. The variable a now holds the value 10, and this value can be used in other parts of the code. This simple example illustrates the basic usage and importance of assignment operators in Python programming.

Types of Assignment Operator in Python

There are several types of assignment operator in Python that are used to perform different operations. Let’s explore each type of assignment operator in Python in detail with the help of some code examples.

1. Simple Assignment Operator (=)

The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is:

Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example

Explanation: In this case, the value 25 is assigned to the variable a using the simple assignment operator. The variable a now holds the value 25.

2. Addition Assignment Operator (+=)

The addition assignment operator is used to add a value to a variable and store the result in the same variable. The syntax for the addition assignment operator is:

Here, the value on the right-hand side is added to the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is incremented by 5 using the addition assignment operator. The result, 15, is then printed to the console.

3. Subtraction Assignment Operator (-=)

The subtraction assignment operator is used to subtract a value from a variable and store the result in the same variable. The syntax for the subtraction assignment operator is

Here, the value on the right-hand side is subtracted from the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is decremented by 5 using the subtraction assignment operator. The result, 5, is then printed to the console.

4. Multiplication Assignment Operator (*=)

The multiplication assignment operator is used to multiply a variable by a value and store the result in the same variable. The syntax for the multiplication assignment operator is:

Here, the value on the right-hand side is multiplied by the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is multiplied by 5 using the multiplication assignment operator. The result, 50, is then printed to the console.

5. Division Assignment Operator (/=)

The division assignment operator is used to divide a variable by a value and store the result in the same variable. The syntax for the division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 5 using the division assignment operator. The result, 2.0, is then printed to the console.

6. Modulus Assignment Operator (%=)

The modulus assignment operator is used to find the remainder of the division of a variable by a value and store the result in the same variable. The syntax for the modulus assignment operator is

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the remainder is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the modulus assignment operator. The remainder, 1, is then printed to the console.

7. Floor Division Assignment Operator (//=)

The floor division assignment operator is used to divide a variable by a value and round the result down to the nearest integer, and store the result in the same variable. The syntax for the floor division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is rounded down to the nearest integer. The rounded result is then stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the floor division assignment operator. The result, 3, is then printed to the console.

8. Exponentiation Assignment Operator (**=)

The exponentiation assignment operator is used to raise a variable to the power of a value and store the result in the same variable. The syntax for the exponentiation assignment operator is:

Here, the variable on the left-hand side is raised to the power of the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is raised to the power of 3 using the exponentiation assignment operator. The result, 8, is then printed to the console.

9. Bitwise AND Assignment Operator (&=)

The bitwise AND assignment operator is used to perform a bitwise AND operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise AND assignment operator is:

Here, the variable on the left-hand side is ANDed with the value on the right-hand side using the bitwise AND operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ANDed with 3 using the bitwise AND assignment operator. The result, 2, is then printed to the console.

10. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator is used to perform a bitwise OR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise OR assignment operator is:

Here, the variable on the left-hand side is ORed with the value on the right-hand side using the bitwise OR operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ORed with 3 using the bitwise OR assignment operator. The result, 7, is then printed to the console.

11. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator is used to perform a bitwise XOR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise XOR assignment operator is:

Here, the variable on the left-hand side is XORed with the value on the right-hand side using the bitwise XOR operator, and the result are stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is XORed with 3 using the bitwise XOR assignment operator. The result, 5, is then printed to the console.

12. Bitwise Right Shift Assignment Operator (>>=)

The bitwise right shift assignment operator is used to shift the bits of a variable to the right by a specified number of positions, and store the result in the same variable. The syntax for the bitwise right shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the right by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is shifted 2 positions to the right using the bitwise right shift assignment operator. The result, 2, is then printed to the console.

13. Bitwise Left Shift Assignment Operator (<<=)

The bitwise left shift assignment operator is used to shift the bits of a variable to the left by a specified number of positions, and store the result in the same variable. The syntax for the bitwise left shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the left by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Conclusion Assignment operator in Python is used to assign values to variables, and it comes in different types. The simple assignment operator (=) assigns a value to a variable. The augmented assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=) perform a specified operation and assign the result to the same variable in one step. The modulus assignment operator (%) calculates the remainder of a division operation and assigns the result to the same variable. The bitwise assignment operators (&=, |=, ^=, >>=, <<=) perform bitwise operations and assign the result to the same variable. The bitwise right shift assignment operator (>>=) shifts the bits of a variable to the right by a specified number of positions and stores the result in the same variable. The bitwise left shift assignment operator (<<=) shifts the bits of a variable to the left by a specified number of positions and stores the result in the same variable. These operators are useful in simplifying and shortening code that involves assigning and manipulating values in a single step.

Here are some Frequently Asked Questions on Assignment Operator in Python:

Q1 – Can I use the assignment operator to assign multiple values to multiple variables at once? Ans – Yes, you can use the assignment operator to assign multiple values to multiple variables at once, separated by commas. For example, "x, y, z = 1, 2, 3" would assign the value 1 to x, 2 to y, and 3 to z.

Q2 – Is it possible to chain assignment operators in Python? Ans – Yes, you can chain assignment operators in Python to perform multiple operations in one line of code. For example, "x = y = z = 1" would assign the value 1 to all three variables.

Q3 – How do I perform a conditional assignment in Python? Ans – To perform a conditional assignment in Python, you can use the ternary operator. For example, "x = a (if a > b) else b" would assign the value of a to x if a is greater than b, otherwise it would assign the value of b to x.

Q4 – What happens if I use an undefined variable in an assignment operation in Python? Ans – If you use an undefined variable in an assignment operation in Python, you will get a NameError. Make sure you have defined the variable before trying to assign a value to it.

Q5 – Can I use assignment operators with non-numeric data types in Python? Ans – Yes, you can use assignment operators with non-numeric data types in Python, such as strings or lists. For example, "my_list += [4, 5, 6]" would append the values 4, 5, and 6 to the end of the list named my_list.

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

Python list functions & python list methods, python interview questions, namespaces and scope in python, what is the difference between append and extend in python, python program to check for the perfect square, python program to find the sum of first n natural numbers.

  • 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 (=)

Arithmetic operators ( +, -, *, /, % ), compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=), increment and decrement (++, --), relational and comparison operators ( ==, =, >, <, >=, <= ), logical operators ( , &&, || ), conditional ternary operator ( ), comma operator ( , ), bitwise operators ( &, |, ^, ~, <<, >> ), explicit type casting operator, other operators, precedence of operators.

CProgramming Tutorial

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

Assignment Operators in C

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

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

Simple assignment operator (=)

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

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

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

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

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

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

Augmented assignment operators

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

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

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

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

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

cppreference.com

Assignment operators.

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

[ edit ] Simple assignment

The simple assignment operator expressions have the form

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

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

rhs and lhs must satisfy one of the following:

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

[ edit ] Notes

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

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

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

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

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

[ edit ] Compound assignment

The compound assignment operator expressions have the form

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

[ edit ] References

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

[ edit ] See Also

Operator precedence

[ edit ] See also

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 19 August 2022, at 08:36.
  • This page has been accessed 54,567 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators

Assignment Operators in C

  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

  • C Structures
  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

highlight the assignment operator (symbol) in the following code

Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

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:

2. “+=” : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right from the current value of the variable on left and then assigns the result to the variable on the left. Example:

If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

Please Login to comment...

Similar reads.

  • C-Operators
  • cpp-operator

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

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

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

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

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

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

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

For example, 3+4 or x*y .

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

For example, x++ or ++x .

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

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

Destructuring

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

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

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

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

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

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

The following table summarizes JavaScript's bitwise operators.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

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

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

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

Bitwise shift operators

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

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

The shift operators are listed in the following table.

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

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

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

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

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

Short-circuit evaluation

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

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

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

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

For example,

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

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

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

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

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

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

A unary operation is an operation with only one operand.

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

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

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

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

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

Deleting array elements

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

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

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

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

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

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

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

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

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

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

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

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

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

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

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

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

Relational operators

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

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

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

The following examples show some uses of the in operator.

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

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

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

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

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

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

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

  • Expressions

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

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

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

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

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

Primary expressions

Basic keywords and general expressions in JavaScript.

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

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

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

  • Grouping operator

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

Comprehensions

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

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

Left values are the destination of an assignment.

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

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

Spread operator

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

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

Similarly, the spread operator works with function calls:

Document Tags and Contributors

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

PW Skills | Blog

Assignment Operators

' src=

Assignment operators play a pivotal role in programming by allowing developers to assign values to variables. These operators are fundamental to most programming languages, including C, C++, Java, etc. In this article, we will explore assignment operators, their types, and how they are used to manipulate data in programs.

Table of Contents

Recommended Course 

  •   Decode DSA with C++
  • Full Stack Data Science Pro Course 
  • Java For Cloud Course 
  • Full Stack Web Development Course
  • Data Analytics Course 

highlight the assignment operator (symbol) in the following code

An assignment operator consists of two operands: the left-side operand (a variable) and the right-side operand (a value). The operator aims to assign the value on the right side to the variable on the left side. However, there’s a crucial rule: the value’s data type on the right side must match the variable’s data type on the left side. If they don’t match, the compiler will generate an error.

Here is a list of common assignment operators:

  • “=” (Simple Assignment Operator)

The most straightforward assignment operator, “=,” assigns the value on the right to the variable on the left. For instance:

int a = 10;

char ch = ‘y’;

In the first line, the variable a is assigned the value 10, while in the second line, the variable ch is assigned the character ‘y’.

  • “+=” (Addition Assignment Operator)

The “+=” operator combines addition and assignment. It adds the current value of the variable on the left to the value on the right and assigns the result back to the variable on the left. It can be expressed as follows:

a += b; // Equivalent to a = a + b;

Suppose the initial value stored in a is 5. After executing (a += 6), a value becomes 11.

  • “-=” (Subtraction Assignment Operator)

The “-=” operator combines subtraction and assignment. It subtracts the current value of the variable on the left from the value on the right and assigns the result back to the variable on the left. It can be expressed as follows:

a -= b; // Equivalent to a = a – b;

If the initial value stored in a is 8, after executing (a -= 6), a value becomes 2.

  • “*=” (Multiplication Assignment Operator)

The “*=” operator combines multiplication and assignment. It multiplies the current value of the variable on the left by the value on the right and assigns the result back to the variable on the left. It can be expressed as follows:

a *= b; // Equivalent to a = a * b;

If the initial value stored in a is 5, after executing (a *= 6), a value becomes 30.

  • “/=” (Division Assignment Operator)

The “/=” operator combines division and assignment. It divides the current value of the variable on the left by the value on the right and assigns the result back to the variable on the left. It can be expressed as follows:

a /= b; // Equivalent to a = a / b;

If the initial value stored in a is 6, after executing (a /= 2), a value becomes 3.

Putting Assignment Operators to Work

To demonstrate the use of assignment operators, let’s consider a simple C program:

#include <stdio.h>

int main() {

    int a = 10;

    printf(“Value of a is %d\n”, a);

    a += 10;

    a -= 10;

    a *= 10;

    a /= 10;

    return 0;

When executed, this program will output the following:

value of a is 10

value of a is 20

value of a is 100

This output illustrates how assignment operators modify variable A’s value through various arithmetic operations. Assignment operators are fundamental tools in programming, allowing developers to manipulate variables by assigning values based on different operations. Understanding these operators’ behavior is crucial for writing efficient and error-free code. As you continue your programming journey, you’ll encounter these operators frequently and become skilled at using them to build robust and dynamic applications.

Assignment Operators Frequently Asked Questions

Q1.  What’s the operator of an assignment? 

Ans. The assignment operator =Assigns the value of its right-hand operand to a variable, property, or indexer element given by a left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.

Q2. What are assignment operators in C++?

Ans. The Assignment Operator in C++ is a Binary Operator that uses the symbol “=.” It requires a variable as the left operand and a value to be assigned as the right operand.

Q3. Define add and assignment operators.

Ans. The add and assignment operator adds the value on the right to the left and stores the result on the left. The subtract and assignment operator subtracts the value on the right from the left and stores the result on the left.

  • Basic Java Programs For Beginners

basic java programs for beginners

Basic Java Programs for Beginners are the gateway to a world of possibilities. They in still confidence, unravel the beauty…

  • 35 Basic Java Program Examples with Outputs

basic java program examples

By practicing basic Java program examples, you'll not only enhance your skills but also gain confidence in your abilities. Experimentation…

  • Best Java Course – Best Java Programming Course

best java course

Java developers are always in demand at top tech companies. Earn some necessary certifications to enhance your resume and validate…

right adv

Related Articles

  • Top 10 Best Place To Learn Java In 2024
  • Basic Java Programs For Practice: Java Array Problems
  • Basic Simple Java Programs, Features, Optimization
  • Basics In Javascript: A Comprehensive Guide
  • Basics Of Programming Java, Syntax, Variables And Data Type
  • Architecture Of Spring MVC: Diagram, Examples & Interview Questions
  • Basic Java Program Code: For Beginners, Interview & Examples

bottom banner

highlight the assignment operator (symbol) in the following code

Secure Your Spot in Our PCA Online Course Starting on April 02 (Click for More Info)

Joachim Schork Image Course

Assignment Operators in R (3 Examples) | Comparing = vs. <- vs. <<-

On this page you’ll learn how to apply the different assignment operators in the R programming language .

The content of the article is structured as follows:

Let’s dive right into the exemplifying R syntax!

Example 1: Why You Should Use <- Instead of = in R

Generally speaking, there is a preference in the R programming community to use an arrow (i.e. <-) instead of an equal sign (i.e. =) for assignment.

In my opinion, it makes a lot of sense to stick to this convention to produce scripts that are easy to read for other R programmers.

However, you should also take care about the spacing when assigning in R. False spacing can even lead to error messages .

For instance, the following R code checks whether x is smaller than minus five due to the false blank between < and -:

A properly working assignment could look as follows:

However, this code is hard to read, since the missing space makes it difficult to differentiate between the different symbols and numbers.

In my opinion, the best way to assign in R is to put a blank before and after the assignment arrow:

As mentioned before, the difference between <- and = is mainly due to programming style . However, the following R code using an equal sign would also work:

In the following example, I’ll show a situation where <- and = do not lead to the same result. So keep on reading!

Example 2: When <- is Really Different Compared to =

In this Example, I’ll illustrate some substantial differences between assignment arrows and equal signs.

Let’s assume that we want to compute the mean of a vector ranging from 1 to 5. Then, we could use the following R code:

However, if we want to have a look at the vector x that we have used within the mean function, we get an error message:

Let’s compare this to exactly the same R code but with assignment arrow instead of an equal sign:

The output of the mean function is the same. However, the assignment arrow also stored the values in a new data object x:

This example shows a meaningful difference between = and <-. While the equal sign doesn’t store the used values outside of a function, the assignment arrow saves them in a new data object that can be used outside the function.

Example 3: The Difference Between <- and <<-

So far, we have only compared <- and =. However, there is another assignment method we have to discuss: The double assignment arrow <<- (also called scoping assignment).

The following code illustrates the difference between <- and <<- in R. This difference mainly gets visible when applying user-defined functions .

Let’s manually create a function that contains a single assignment arrow:

Now, let’s apply this function in R:

The data object x_fun1, to which we have assigned the value 5 within the function, does not exist:

Let’s do the same with a double assignment arrow:

Let’s apply the function:

And now let’s return the data object x_fun2:

As you can see based on the previous output of the RStudio console, the assignment via <<- saved the data object in the global environment outside of the user-defined function.

Video & Further Resources

I have recently released a video on my YouTube channel , which explains the R syntax of this tutorial. You can find the video below:

The YouTube video will be added soon.

In addition to the video, I can recommend to have a look at the other articles on this website.

  • R Programming Examples

In summary: You learned on this page how to use assignment operators in the R programming language. If you have further questions, please let me know in the comments.

assignment-operators-in-r How to use different assignment operators in R – 3 R programming examples – R programming language tutorial – Actionable R programming syntax in RStudio

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy .

Leave a Reply Cancel reply

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

Post Comment

Joachim Schork Statistician Programmer

I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.

Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy .

Related Tutorials

Don’t Display Data Frame Row Names in R (Example)

Don’t Display Data Frame Row Names in R (Example)

The nrow Function in R (4 Examples)

The nrow Function in R (4 Examples)

Popular Coding Symbols in Programming Languages self.__wrap_b=(t,n,e)=>{e=e||document.querySelector(`[data-br="${t}"]`);let a=e.parentElement,r=R=>e.style.maxWidth=R+"px";e.style.maxWidth="";let o=a.clientWidth,c=a.clientHeight,i=o/2-.25,l=o+.5,u;if(o){for(;i+1 {self.__wrap_b(0,+e.dataset.brr,e)})).observe(a):process.env.NODE_ENV==="development"&&console.warn("The browser you are using does not support the ResizeObserver API. Please consider add polyfill for this API to avoid potential layout shifts or upgrade your browser. Read more: https://github.com/shuding/react-wrap-balancer#browser-support-information"))};self.__wrap_b(":R4mr36:",1)

Vishnupriya's profile image

Basic Symbols and Their Functions

Symbols for comparison and logic, assignment and special operators, advanced symbol usage, cross-language symbol comparison, best practices.

Popular Coding Symbols in Programming Languages

Welcome to the intricate world of coding symbols in programming languages! If you’re a coding enthusiast, a student, or a professional developer, you already know that coding is not just about typing commands; it’s about understanding the language of the computer. Symbols in programming are like the punctuation marks in a written language—they give structure, meaning, and clarity to our code. Whether you’re learning through platforms like codedamn or diving into documentation, a solid grasp of these symbols is crucial for efficient and error-free coding.

In this section, we’ll dive into the basic symbols that form the backbone of many programming languages. These symbols might seem small and insignificant, but they play a major role in how a program functions. Let’s explore some of these symbols and understand their importance.

Semicolon (;)

The semicolon is a critical symbol in many programming languages, including C, C++, and Java. It’s used to mark the end of a statement, much like a period in a sentence. This tells the compiler or interpreter where one statement ends and another begins, helping to avoid confusion and errors. For instance, in JavaScript, a semicolon is used to separate statements, although it’s often optional due to Automatic Semicolon Insertion (ASI). However, relying on ASI can sometimes lead to unexpected results, so it’s generally good practice to include semicolons explicitly.

Parentheses (())

Parentheses are used in virtually all programming languages, and their role can vary depending on the context. They are commonly used in function calls and definitions, where they enclose arguments or parameters. For example, print("Hello, World!") in Python uses parentheses to hold the string that the print function will output. They’re also crucial in controlling the order of operations in mathematical expressions, just like in algebra.

The plus symbol is most commonly associated with addition in mathematics, and this holds true in programming as well. In many languages like Python, Java, and JavaScript, the plus symbol is used for adding numbers. But its role doesn’t stop there. In languages like JavaScript, the plus symbol can also be used for string concatenation, meaning it can combine two strings into one. For instance, "Hello " + "World!" results in "Hello World!" . It’s a versatile symbol with multiple uses depending on the context.

Now, let’s turn our attention to symbols that are used for comparison and logical operations. These symbols are essential for making decisions in code and controlling the flow of execution based on certain conditions.

Equality (==) and Inequality (!=) Operators

Equality ( == ) and inequality ( != ) operators are fundamental in programming languages like JavaScript, Python, and many others. They are used to compare values. The equality operator ( == ) checks if the values on either side are equivalent, while the inequality operator ( != ) checks if they are not. It’s important to note that == in JavaScript does type coercion, which can lead to unexpected results. For strict comparison, === is used, which compares both value and type.

Logical And (&) and Or (||)

Logical operators such as And ( & ) and Or ( || ) play a pivotal role in decision-making in programming. They are used to combine multiple conditions. In a logical AND operation, the result is true if all conditions are true. In contrast, the logical OR operation yields true if at least one of the conditions is true. These operators are widely used in programming languages like C++, Java, and JavaScript for constructing complex logical expressions.

In the world of programming, understanding the significance and functionality of various symbols is crucial. These symbols, often compact and seemingly simple, carry a great deal of meaning and are fundamental in structuring and executing code effectively. In this section, we’ll dive into some of the commonly used assignment and special operators, exploring their roles and nuances across different programming languages.

Assignment Operator (=)

The assignment operator, represented by the equal sign = , is one of the most fundamental symbols in programming. It is used to assign values to variables. In most languages, the operator takes the value on its right and stores it in the variable on its left. For instance, x = 5 assigns the value 5 to the variable x . It’s essential to differentiate between the assignment operator and the equality operator (== in many languages), which is used for comparison.

Dollar Sign ($)

The dollar sign $ holds a special place in several programming languages, notably PHP. In PHP, the dollar sign is used to denote variables. For example, $username represents a variable named ‘username’. Its use simplifies the process of variable identification and differentiation from other elements in the code. This specific use of the dollar sign is unique to PHP and a few other languages, marking a distinctive syntax feature.

Braces ({})

Braces, or curly brackets {} , are versatile symbols used across various programming languages with multiple purposes. In languages like C, C++, and Java, braces define the scope of code blocks, encapsulating functions, loops, and conditional statements. They help in structuring the code, making it readable and maintainable. For instance, in a function definition, the code within the braces is the function body. Braces also play a significant role in object and array initializations in languages like JavaScript and Python.

As we delve deeper into programming, we encounter symbols that play more specialized roles, often pivotal in advanced coding techniques and structures. These symbols contribute to the efficiency and sophistication of the code, enabling programmers to implement complex logic and functionalities.

Scope Resolution (::)

The scope resolution operator, denoted by :: , is used in languages like C++ to access static, constant, and overridden members of a class. For example, ClassName::staticMethod() allows access to a static method of a class without needing to instantiate it. This operator is essential for namespace management and accessing class members in an unambiguous way, especially in large-scale projects where name conflicts might arise.

Arrow (->)

The arrow symbol -> is used in several programming contexts. In C++, it is used to access members of a structure or a class through a pointer. For example, ptr->func() calls the function func() on the object that ptr points to. In languages like PHP, it serves a similar purpose, accessing an object’s properties or methods. The arrow operator provides a concise and clear syntax for pointer and object manipulation.

Programming languages, while sharing some common syntax elements, often utilize symbols differently, offering a rich diversity in coding approaches. This section compares how certain symbols are used across various programming languages, highlighting their unique applications and functionalities.

Symbol Usage in Different Languages

A comparative analysis of symbol usage across languages reveals intriguing differences and similarities. For example, the colon symbol : has varied uses – in Python, it denotes the start of an indented block following structures like loops and conditionals, while in JavaScript, it’s used in object literals to separate keys from values. Similarly, brackets [] are used for array indexing in languages like C and Java, but in Python, they define a list.

Effective symbol usage in programming is not just about understanding their functionality but also about employing them in a way that enhances code clarity, maintainability, and efficiency. Some best practices include:

  • Use clear and consistent naming conventions for variables and functions.
  • Avoid overusing symbols in a way that makes the code cryptic or unreadable.
  • Understand the nuances of symbol usage in the specific language you’re working with.
  • Regularly refactor code to improve its structure and readability.

Symbols in programming languages are like the nuts and bolts in machinery – small but essential. Their proper usage is key to writing efficient, readable, and maintainable code. This exploration of various symbols across different languages underscores the importance of understanding their context-specific applications and nuances.

Sharing is caring

Did you like what Vishnupriya wrote? Thank them for their work by sharing it on social media.

No comment s so far

IMAGES

  1. Operators in C Programming

    highlight the assignment operator (symbol) in the following code

  2. [100% Working Code]

    highlight the assignment operator (symbol) in the following code

  3. Assignment Operators in C

    highlight the assignment operator (symbol) in the following code

  4. Assignment Operators in C » PREP INSTA

    highlight the assignment operator (symbol) in the following code

  5. C# Assignment Operator

    highlight the assignment operator (symbol) in the following code

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

    highlight the assignment operator (symbol) in the following code

VIDEO

  1. Alphabetic Symbol

  2. Core

  3. Logical AND & OR Operators in Python

  4. C++ Assignment Operators Practice coding

  5. Python operators Part-4 #learnpython #pythonlearning #python3#pythonoperators#pythonforbeginners

  6. C++ Variables, Literals, an Assignment Statements [2]

COMMENTS

  1. Python's Assignment Operator: Write Robust Assignments

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

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

  3. 4.6: Assignment Operator

    But bite your tongue, when you see the = symbol you need to start thinking: assignment. The assignment operator has two operands. The one to the left of the operator is usually an identifier name for a variable. The one to the right of the operator is a value. Simple Assignment int age; // variable set up // then later in the program age = 21;

  4. Assignment Operators in Python

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

  5. 3.5: Assignment Operator

    Discussion. The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol.

  6. C Assignment Operators

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

  7. Python Assignment Operator

    All assignment operators are used to assign values to variables. Wait, is there more than one assignment operator? Yes, but they're all quite similar to the ones you've seen. You've used the most common assignment operator, and its symbol is a single equals sign (=). For example, to assign x the value of 10 you type the following: x = 10

  8. Assignment Operator in Python

    The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is: variable = value. Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example.

  9. Assignment operators

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

  10. Python

    The following code snippet uses the assignment operator, =, to set my_variable to the value of num1 and num2 with an arithmetic operator acting on them. For example, if operator represented *, my_variable would be assigned a value of num1 * num2. my_variable = num1 operator num2 Python operators can be organized into the following groups:

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

  12. JavaScript Assignment Operators

    Addition Assignment Operator ( +=) JavaScript has a variety of operators that allow you to modify a value on assignment. This operator allows you to increase the left-side operand by adding the right-side operand. In this example, we will start by declaring a variable with the name " x ", and assign it the value of 10.

  13. Java Assignment Operators with Examples

    variable operator value; Types of Assignment Operators in Java. The Assignment Operator is generally of two types. They are: 1. Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

  14. Operators

    Operators Once introduced to variables and constants, we can begin to operate with them by using operators. What follows is a complete list of operators. At this point, it is likely not necessary to know all of them, but they are all listed here to also serve as reference. Assignment operator (=) The assignment operator assigns a value to a ...

  15. Assignment Operators in C

    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 −

  16. operators

    1. Most sources online call = (and +=, -=, etc...) an assignment operator (for python). This makes sense in most languages, however, not in python. An operator takes one or more operands, returns a value, and forms an expression. However, in python, assignment is not an expression, and assignment does not yield a value.

  17. Assignment operators

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

  18. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  19. Assignment Operators in C

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

  20. Expressions and operators

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

  21. Assignment Operators

    The Assignment Operator in C++ is a Binary Operator that uses the symbol "=." It requires a variable as the left operand and a value to be assigned as the right operand. Q3. Define add and assignment operators. Ans. The add and assignment operator adds the value on the right to the left and stores the result on the left.

  22. Assignment Operators in R (3 Examples)

    On this page you'll learn how to apply the different assignment operators in the R programming language. The content of the article is structured as follows: 1) Example 1: Why You Should Use <- Instead of = in R. 2) Example 2: When <- is Really Different Compared to =. 3) Example 3: The Difference Between <- and <<-. 4) Video ...

  23. Popular Coding Symbols in Programming Languages

    These symbols, often compact and seemingly simple, carry a great deal of meaning and are fundamental in structuring and executing code effectively. In this section, we'll dive into some of the commonly used assignment and special operators, exploring their roles and nuances across different programming languages. Assignment Operator (=)