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 - Scope Rules
  • C - Pointers
  • C - Strings
  • C - 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

CsTutorialPoint - Computer Science Tutorials For Beginners

Assignment Operators In C [ Full Information With Examples ]

Assignment Operators In C

Assignment Operators In C

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

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

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

x = y = z = 100

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

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

  • Simple assignment operator
  • Compound assignment operators

1. Simple Assignment Operator In C

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

2. Compound Assignment Operators In C

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

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

Look at these two statements:

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

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

Syntax of Compound Assignment Operators

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

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

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

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

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

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

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

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

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

List of Assignment Operators In C

Read More -:

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

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

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

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

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

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

' src=

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

Leave a Reply Cancel reply

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

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

This browser is no longer supported.

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

C Assignment Operators

  • 6 contributors

An assignment operation assigns the value of the right-hand operand to the storage location named by the left-hand operand. Therefore, the left-hand operand of an assignment operation must be a modifiable l-value. After the assignment, an assignment expression has the value of the left operand but isn't an l-value.

assignment-expression :   conditional-expression   unary-expression assignment-operator assignment-expression

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

The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators:

In assignment, the type of the right-hand value is converted to the type of the left-hand value, and the value is stored in the left operand after the assignment has taken place. The left operand must not be an array, a function, or a constant. The specific conversion path, which depends on the two types, is outlined in detail in Type Conversions .

  • 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

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.

Codeforwin

Assignment and shorthand assignment operator in C

Quick links.

  • Shorthand assignment

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

For example consider the below assignment table.

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

Shorthand assignment operator

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

For example, consider following C statements.

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

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

C Programming Tutorial

  • Assignment Operator in C

Last updated on July 27, 2020

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

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

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

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

here x , y and z are initialized to 100 .

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

Note that expressions like:

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

then the assignment expression becomes assignment statement.

Compound Assignment Operator #

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

Consider the following two statements:

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

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

The general format of compound assignment operator is as follows:

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

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

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

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

Similarly, the statement:

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

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

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

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

The following table lists some Compound assignment operators:

The following program demonstrates Compound assignment operators in action:

Expected Output:

Load Comments

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

Recent Posts

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

C Operators

C programming language has a rich set of operators that are used to manipulate variables and perform operations in a program. Operators are symbols that are used to perform arithmetic, logical, and bitwise operations on variables. In this article, we will explore the different types of operators in C programming language and their usage with examples.

Arithmetic Operators

Relational operators, logical operators, bitwise operators, assignment operators.

Arithmetic operators are used in C programming to perform mathematical operations such as addition, subtraction, multiplication, division, and modulo. In this article, we will discuss the different arithmetic operators used in C programming along with their examples.

The arithmetic operators in C programming include:

Addition operator (+), subtraction operator (-), multiplication operator (*), division operator (/), modulo operator (%).

Let’s take a closer look at each of these operators and their usage in C programming with examples.

The addition operator in C programming is represented by the “+” symbol. It is used to add two or more operands together. The operands can be either constants or variables.

For example, if we have two variables a and b, we can use the addition operator + to add them together as follows:

Here’s an example:

Code Example:

The subtraction operator in C programming is represented by the “-” symbol. It is used to subtract the second operand from the first operand. The operands can be either constants or variables.

For example, if we have two variables a and b, we can use the subtraction operator - to subtract b from a as follows:

The multiplication operator in C programming is represented by the “*” symbol. It is used to multiply two or more operands together. The operands can be either constants or variables.

For example, if we have two variables a and b, we can use the multiplication operator * to multiply them together as follows:

The division operator in C programming is represented by the “/” symbol. It is used to divide the first operand by the second operand. The operands can be either constants or variables.

For example, if we have two variables a and b, we can use the division operator / to divide a by b as follows:

It’s important to note that division in C programming is an integer division by default, meaning that any remainder is truncated. If we want to perform a floating-point division, we can cast the variables to float or double as follows:

The modulo operator in C programming is represented by the “%” symbol. It is used to find the remainder of the division of the first operand by the second operand. The operands can be either constants or variables.

For example, if we have two variables a and b, we can use the modulus operator % to get the remainder of a divided by b as follows:

The modulus operator is often used to check if a number is even or odd, as follows:

Order of Precedence

Like in algebra, arithmetic operators in C programming also follow a specific order of precedence. The order of precedence is as follows:

  • Parentheses
  • Multiplication and division (from left to right)
  • Addition and subtraction (from left to right)

Here’s an example of the order of precedence:

Relational operators in C are used to compare two values and return a Boolean value (true or false) depending on the comparison result. The relational operators are often used in conditional statements and loops to compare values and make decisions based on the comparison result.

The relational operators in C programming include:

Greater than operator (>), less than operator (<), greater than or equal to operator (>=).

  • Less than or equal to operator (<=)
  • Equality operator (==)
  • Not equal to operator (!=)

Let’s understand each of these c operators with examples:

The greater than operator compares the left operand with the right operand and returns true if the left operand is greater than the right operand, otherwise, it returns false.

In this example, the condition (a > b) is true, so the message “a is greater than b” will be printed.

The less than operator compares the left operand with the right operand and returns true if the left operand is less than the right operand, otherwise, it returns false.

In this example, the condition (a < b) is false, so the message “b is less than a” will be printed.

The greater than or equal to operator compares the left operand with the right operand and returns true if the left operand is greater than or equal to the right operand, otherwise, it returns false.

In this example, the condition (a >= b) is true, so the message “a is greater than or equal to b \n a is greater than or equal to c” will be printed.

Less Than or Equal To Operator (<=)

The less than or equal to operator compares the left operand with the right operand and returns true if the left operand is less than or equal to the right operand, otherwise, it returns false.

In this example, the condition (a <= c) is true, so the message “a is less than or equal to c” will be printed.

Equality Operator (==)

The equal to operator compares the left operand with the right operand and returns true if they are equal, otherwise, it returns false.

In this example, the condition (a == c) is true, so the message “a is equal to c” will be printed.

Not Equal To Operator (!=)

The not equal to operator compares the left operand with the right operand and returns true if they are not equal, otherwise, it returns false.

In this example, the condition (a != b) is true, so the message “a is not equal to b” will be printed.

Finally, let’s combine these operators in an example:

In the above example, we have used the logical AND (&&) and logical OR (||) operators to combine the relational operators. The logical AND operator returns true if both the expressions on its left and right sides are true. Similarly, the logical OR operator returns true if at least one of the expressions on its left and right sides is true.

Logical operators in C programming are used to combine multiple conditions or expressions and evaluate them as a single Boolean value (true or false). The logical operators are often used in conditional statements and loops to make complex decisions based on multiple conditions.

The logical operators in C programming include:

  • Logical AND operator (&&)
  • Logical OR operator (||)
  • Logical NOT operator (!)

Logical AND Operator (&&)

The logical AND operator is used to combine two conditions and evaluate them as a single Boolean value. The resulting value is true only if both conditions are true.

In this example, the condition (a < b && b > 0) is true, so the message “a is less than b and b is positive” will be printed.

Logical OR Operator (||)

The logical OR operator is used to combine two conditions and evaluate them as a single Boolean value. The resulting value is true if either one of the conditions is true.

In this example, we have a variable called num which has a value of 5. We want to check if num is within the range of 0 to 10, so we use the logical OR operator || to combine two conditions:

Logical NOT Operator (!)

The logical NOT operator is used to reverse the Boolean value of a condition or expression.

In this example, the condition !(a < b) is false (because a < b is true), so the message “a is not less than b” will not be printed.

It is important to note that logical operators in C have short-circuit behavior, meaning that if the value of a condition can be determined by only evaluating the first part of the condition, the second part of the condition is not evaluated. This can help improve the performance of your code.

In C programming, bitwise operators are used to manipulate the individual bits of a value. The bitwise operators are applied to binary values and return a new binary value that represents the result of the operation.

The bitwise operators in C programming include:

Bitwise and operator (&), bitwise or operator (|), bitwise xor operator (^), bitwise not operator (~), left shift operator (<<), right shift operator (>>).

The bitwise AND operator takes two binary values and returns a new binary value in which each bit is 1 only if both corresponding bits in the original values are 1.

In this example, we have two variables num1 and num2 which have the values 14 and 6 respectively. These values are represented in binary form as 1110 and 0110.

We want to perform a bitwise AND operation on num1 and num2. To do this, we use the bitwise AND operator &. The result of the bitwise AND operation is a new binary value in which each bit is 1 only if both corresponding bits in the original values are 1.

In this case, the result of the bitwise AND operation is 0110, which is equivalent to the decimal value 6. This is because the first and third bits of both num1 and num2 are 1, while the second and fourth bits are 0.

The bitwise OR operator takes two binary values and returns a new binary value in which each bit is 1 if either one or both corresponding bits in the original values are 1.

In this example, we have two variables num1 and num2 which have the values 10 and 6 respectively. These values are represented in binary form as 1010 and 0110.

We want to perform a bitwise OR operation on num1 and num2. To do this, we use the bitwise OR operator |. The result of the bitwise OR operation is a new binary value in which each bit is 1 if either one or both corresponding bits in the original values are 1.

In this case, the result of the bitwise OR operation is 1110, which is equivalent to the decimal value 14. This is because the first, second, and fourth bits of num1 are 1, and the second and third bits of num2 are also 1.

The bitwise XOR operator takes two binary values and returns a new binary value in which each bit is 1 only if exactly one of the corresponding bits in the original values is 1.

We want to perform a bitwise XOR operation on num1 and num2. To do this, we use the bitwise XOR operator ^. The result of the bitwise XOR operation is a new binary value in which each bit is 1 only if exactly one of the corresponding bits in the original values is 1.

In this case, the result of the bitwise XOR operation is 1100, which is equivalent to the decimal value 12. This is because the first, second, and fourth bits of num1 are 1, and the second and third bits of num2 are 1, but the first and fourth bits of num2 are 0.

The bitwise NOT operator takes a single binary value and returns a new binary value in which each bit is the complement of the corresponding bit in the original value (i.e., 0 becomes 1 and 1 becomes 0).

In this example, we have a variable num which has the value 10. This value is represented in binary form as 0000 1010.

We want to perform a bitwise NOT operation on num. To do this, we use the bitwise NOT operator ~. The result of the bitwise NOT operation is a new binary value in which each bit is the complement of the corresponding bit in the original value (i.e., 0 becomes 1 and 1 becomes 0).

In this case, the result of the bitwise NOT operation is 1111 0101, which is equivalent to the decimal value 245. This is because each bit in the original value is flipped to its opposite value.

The left shift operator takes two binary values and returns a new binary value in which each bit is shifted to the left by a specified number of positions.

We want to perform a left shift operation on num by 2 positions. To do this, we use the left shift operator << . The result of the left shift operation is a new binary value in which each bit is shifted to the left by a specified number of positions.

In this case, the result of the left shift operation is 0010 1000, which is equivalent to the decimal value 40. This is because each bit in the original value is shifted 2 positions to the left.

The right shift operator takes two binary values and returns a new binary value in which each bit is shifted to the right by a specified number of positions.

We want to perform a right shift operation on num by 2 positions. To do this, we use the right shift operator >>. The result of the right shift operation is a new binary value in which each bit is shifted to the right by a specified number of positions.

In this case, the result of the right shift operation is 0000 0010, which is equivalent to the decimal value 2. This is because each bit in the original value is shifted 2 positions to the right.

In C programming, assignment operators are used to assign a value to a variable. The most commonly used assignment operator is the = operator, but there are also other assignment operators that perform arithmetic or bitwise operations in conjunction with assignment. These operators include:

The assignment operators in C programming include:

Simple assignment operator (=), 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 (>>=).

The simple assignment operator is used to assign a value to a variable.

In this example, the value 10 is assigned to the variable x.

The addition assignment operator is used to add a value to a variable and assign the result back to the same variable.

In this example, the value of x is incremented by 5, resulting in a new value of 15.

The subtraction assignment operator is used to subtract a value from a variable and assign the result back to the same variable.

In this example, the value of x is decremented by 3, resulting in a new value of 7.

The multiplication assignment operator is used to multiply a variable by a value and assign the result back to the same variable.

In this example, the value of x is multiplied by 2, resulting in a new value of 20.

The division assignment operator is used to divide a variable by a value and assign the result back to the same variable.

In this example, the value of x is divided by 3, resulting in a new value of 3.

The modulus assignment operator is used to calculate the remainder of dividing a variable by a value and assign the result back to the same variable.

In this example, the value of x is divided by 3, and the remainder is assigned back to x, resulting in a new value of 1.

The bitwise AND assignment operator is used to perform a bitwise AND operation between a variable and a value, and assign the result back to the same variable.

In this example, the bitwise AND operation is performed between the binary value of x and 0b11110000, resulting in the new binary value 0b10100000, which is then assigned back to x. Finally, the new value of 160

The bitwise OR assignment operator is used to perform a bitwise OR operation between a variable and a value, and assign the result back to the same variable.

In this example, the bitwise OR operation is performed between the binary value of x and 0b00001111, resulting in the new binary value 0b10101111, which is then assigned back to x.Finally, the new value of 175

The bitwise XOR assignment operator is used to perform a bitwise XOR operation between a variable and a value, and assign the result back to the same variable.

In this example, the bitwise XOR operation is performed between the binary value of x and 0b11001100, resulting in the new binary value 0b01100110, which is then assigned back to x. Finally, the new value of 102

The left shift assignment operator is used to shift the bits of a variable to the left by a specified number of positions, and assign the result back to the same variable.

In this example, the bits of the binary value of x are shifted two positions to the left, resulting in the new binary value 0b1010101000, which is then assigned back to x. Finally, the new value of 680

The right shift assignment operator is used to shift the bits of a variable to the right by a specified number of positions, and assign the result back to the same variable.

In this example, the bits of the binary value of x are shifted two positions to the right, resulting in the new binary value 0b00101010, which is then assigned back to x. Finally, the new value of 42

In this article, we have explored the different types of operators available in the C programming language, along with examples of each type. Operators are fundamental building blocks of programming, and understanding how to use them effectively is crucial for writing efficient and effective code.

Arithmetic operators are used to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. Assignment operators are used to assign a value to a variable. Comparison operators are used to compare two values and return a Boolean value. Logical operators are used to perform logical operations and return a Boolean value. Bitwise operators are used to perform operations on individual bits of integer data types.

It’s important to note that operators have an order of precedence, meaning that some operators will be evaluated before others. For example, multiplication and division will be evaluated before addition and subtraction. If you want to change the order of precedence, you can use parentheses to group operations.

Operators are a crucial part of C programming, and understanding how to use them effectively is key to writing efficient and effective code. By mastering the different types of operators and their uses, you can create complex programs that accomplish a wide variety of tasks.

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

C Functions

C structures, c operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

C divides the operators into the following groups:

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

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0 , which means true ( 1 ) or false ( 0 ). These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

Comparison operators are used to compare two values.

Note: The return value of a comparison is either true ( 1 ) or false ( 0 ).

In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:

A list of all comparison operators:

Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

C Exercises

Test yourself with exercises.

Fill in the blanks to multiply 10 with 5 , and print the result:

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

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

assignment operators in c programming with examples

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.

The Simple Assignment Operator

  • The equals sign, =, is known as the assignment operator in C
  • The purpose of the assignment operator is to take the value from the right hand side of the operator ( the RHS value ), and store it in the variable on the left hand side ( the LHS ).
  • X = Y + 7; - Valid: The sum of Y plus 7 will be stored in the variable X.
  • X - Y = 7; - Invalid: Although this looks like a simple rearrangement of the above, the LHS is no longer a valid storage location.
  • 7 = X - Y; - Invalid: The LHS is now a single entity, but it is a constant whose value cannot be changed.
  • X = X + 7; - Valid: First the original value of X will be added to 7. Then this new total will be stored back into X, replacing the previous value.

Arithmetic Operators, +, -, *, /, %

  • Ex: X = Y + 7;
  • Ex: X = Y - 7;
  • Ex: X = - Y;
  • ( + can also be used as a unary operator, but there is no good reason to do so. )
  • Ex: X = Y * 7;
  • Ex: X = Y / 7;
  • 9 / 10 yields zero, not 0.9 or 1.
  • 17 / 5 yields 3.
  • 9.0 / 10 yields 0.9, because there are two different types involved, and so the "smaller" int of 10 is promoted to a double precision 10.0 before the division takes place.
  • int num = 9.0 / 10; stores 0. The division yields 0.9 as in the above example, but then it is truncated to the integer 0 by the assignment operator that stores the result in the int variable "num".
  • Ex: K = N % 7;
  • 17 % 5 yields 2.
  • 3 % 5 yields 3.
  • Mod only works with integers in C.
  • If N % M is equal to zero, then it means N is evenly divisible by M. ( E.g. if N % 2 is 0, then N is even. )
  • Therefore mod is often used to map a number into a given range.
  • For example, rand( ) % 52 always yields a number in the range 0 to 51 inclusive, suitable for randomly selecting a card from a deck of 52 cards.

Precedence and Associativity

  • Ex: what is the value of the expression 3 + 5 / 2 ?
  • Assignment statements have the lowest precedence of all, so all other operations are performed before the result is assigned.
  • Ex: In the expression 3 * ( 4 + 2 ), the addition is performed first, and then the multiplication.
  • Ex: What is the value of the expression 5 / 3 * 2.0 ?
  • A = B = C = 0;
  • A full table of precedence and associativity is included in any good book on C Programming. There are also many versions of this information on the web.

Abbreviated Assignment Operators

  • E.g. X = X + 7;
  • Because this is so common, there are a number of operators that combine assignment with some other ( binary ) operator.
  • Note that in these combined operators, that there is no space between the = and the other character, e.g. no space between the + and the = in +=.
  • X *= 3 + 4;
  • The above is equivalent to X = X * ( 3 + 4 );, not X = X * 3 + 4;

Auto Increment and Auto Decrement

  • Another operation that is very common in programming is to either increase or decrease an integer by exactly 1, e.g. when counting up or counting down.
  • N++; is equivalent to N += 1; which is equivalent to N = N + 1;
  • N--; is equivalent to N -= 1; which is equivalent to N = N - 1;
  • There are actually two versions of the auto increment/decrement operators, depending on whether the operator appears after the operand ( postfix, e.g. N++ ) or before the operand ( prefix, e.g. ++N ).
  • For stand-alone statement that consist of nothing but the auto increment/decrement there is no difference between the two. Common convention is to use the postfix form, but prefix would work equivalently.
  • If N is originally equal to 3, then the statement X = 2 * N++ * 3; will store 18 in X and then increment N to 4.
  • If N is originally equal to 3, then the statement X = 2 * ++N * 3; will increment N to 4 first, and then store 24 in X.
  • DANGER: If a variable is affected by an auto increment / decrement operator, never use that same variable more than once in the same statement. For example, the result of X = N++ * 3 + N; is undefined, because it is undetermined what value will be used for the second instance of N.
  • ( Compare N++ +J to N+ ++J )

Tutorials Maker

Assignment operators in C | C Operators and Expressions

Assignment operators in C | C Operators and Expressions

C programming assignment operators; In this tutorial, you will learn about assignment operators in c programming with examples.

C Assignment Operators

An assignment operator is used for assigning a value to a variable in c programming language.

List of Assignment Operators in C

Note that:- There are 2 categories of assignment operators in C language. Shown below:

  • 1. Simple assignment operator ( Example: = )
  • 2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )

Example 1 – Assignment Operators

Note that:- The left side operand of the assignment operator is a variable and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type as the variable on the left side otherwise the compiler will raise an error.

assignment operators in c programming with examples

Author Admin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

View all posts by Admin

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.

Javatpoint Logo

  • Design Pattern
  • Interview Q

C Control Statements

C functions, c dynamic memory, c structure union, c file handling, c preprocessor, c command line, c programming test, c interview.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Software Engineering
  • Mukesh kumar Created by
  • 4 (4586 ratings)
  • 965 Comments
  • 17/11/2023 Last Updated

1. Introduction

2. History of C Language

3. Features of C Language

4. Use of C Language

5. C Language Download

6. Coding Vs. Programming

7. Structures in C

8. Difference Between Compiler and Interpreter

9. Difference Between Arguments And Parameters

10. C Program to Find ASCII Value of a Character

11. Define And include in C

12. What is Variables in C

13. Boolean in C

14. Conditional Statements in C

15. Constants in C

16. Data Types in C

17. Switch Case in C

18. Data Structures in C

19. C Compiler for Windows

20. C Compiler for Mac

21. Compilation process in C

22. Storage Classes in C

23. Array in C

24. One Dimensional Array in C

25. Two Dimensional Array in C

26. Dynamic Array in C

27. Array of Structure in C

28. Length of an Array in C

29. Array of Pointers in C

30. If Else Statement in C

31. Nested if else statement in C

32. Do While Loop In C

33. Nested Loop in C

34. For Loop in C

35. Difference Between If Else and Switch

36. If Statement in C

37. Operators in C

38. Bitwise Operators in C

39. C Ternary Operator

40. Logical Operators in C

41. Increment and decrement operators in c

42. Conditional operator in the C

43. Relational Operators in C

44. Assignment Operator in C

45. Unary Operator in C

46. Operator Precedence and Associativity in C

47. String Functions in C

48. String Input Output Functions in C

49. Function Pointer in C

50. Functions in C

51. Input and Output Functions in C

52. User Defined Functions in C

53. C Function Call Stack

54. Static function in C

55. Library Function in C

56. Toupper Function in C

57. Ceil Function in C

58. C string declaration

59. String Length in C

60. String Comparison in C

61. Pointers in C

62. Dangling Pointer in C

63. Pointer to Pointer in C

64. Constant Pointer in C

65. String Pointer in C

66. File Handling in C

67. Header Files in C

68. Stack in C

69. Stack Using Linked List in C

70. Linked list in C

71. Implementation of Queue Using Linked List

72. Heap Sort in C Program

73. Tokens in C

74. Enumeration (or enum) in C

75. Format Specifiers in C

76. Strcpy in C

77. Type Casting in C

78. Stdio.h in C

79. Transpose of a Matrix in C

80. Jump Statements in C

81. goto statement in C

82. Double In C

83. Comments in C

84. Types of Error in C

85. strcat() in C

86. Binary to Decimal in C

87. Pre-increment And Post-increment

88. C/C++ Preprocessors

89. How To Install C Language In Mac

90. Evaluation of Arithmetic Expression

91. Random Number Generator in C

92. Random Access Files in C

93. Pattern Programs in C

94. Palindrome Program in C

95. Prime Number Program in C

96. Hello World Program in C

97. Simple interest program in C

98. Anagram Program in C

99. Calculator Program in C

100. C Hello World Program

101. Structure of C Program

102. Program for Linear Search in C

103. C Program for Bubble Sort

104. C Program for Factorial

105. C Program for Prime Numbers

106. Reverse a String in C

107. C Program to Reverse a Number

108. C Program for String Palindrome

109. Debugging C Program

110. How to compile a C program in Linux

111. How to Find a Leap Year Using C Programming

112. Lcm of Two Numbers in C

113. Addition of Two Numbers in C

114. Armstrong Number in C

115. Recursion in C

116. Binary Search in C

117. Matrix multiplication in C

118. Overflow And Underflow in C

119. Dynamic Memory Allocation in C

120. Pseudo-Code In C

121. Fibonacci Series Program in C Using Recursion

122. Macros in C

123. Call by Value and Call by Reference in C

124. Identifiers in C

125. Factorial of A Number in C

126. strlen() in C

127. Convert Decimal to Binary in C

128. Command Line Arguments in C/C++

129. Strcmp in C

130. Square Root in C

Assignment Operator in C

Assignment operators play a vital role in the C programming language, allowing programmers to assign variable values. Understanding assignment operators is crucial for mastering the art of variable manipulation in C. So, let's begin our exploration of assignment operators

This article will explore the world of assignment operators in C, exploring their various types and providing illustrative examples.

What is Assignment Operator in C?

Assignment operators are binary operators in C that enable us to give values or expressions to variables. In C, assignment operators associate from right to left, resulting in the value on the right being assigned to the variable on the left. The variable is always on the left side (LHS), while the value or expression is on the assignment operator's right side (RHS). 

Assignment operators have lower precedence levels compared to other operators in C. You can assign the same value to multiple variables in a single line of code, and the assignment is performed from right to left. The most basic assignment operator symbol is =, which requires two operands.

Let’s check an example of assignment operator in c - 

In an expression like x = 4, the variable x is assigned 4. The variable is on the left side (LHS), and the value or expression is on the assignment operator's right side (RHS). For example:

The assignment operator associates from right to left. For example:

Here, the value 10 is assigned to y first, and then y's value is assigned to x. The simplest explanation of assignment operator associativity can be represented as:

This shows that assignment operators are binary operators, requiring two operands. The LHS operand must be a variable, and the RHS operand can be a constant, variable, or expression.

assignment operators in c programming with examples

Left Operand = Right Operand

List of All Assignment Operators in C 

In C, we have two types of assignment operators in C: simple assignment operators and compound assignment operators.

Simple Assignment Operator (=):

A simple assignment operator assigns the value on the right-hand side (RHS) to the variable on the left-hand side (LHS)

For example:

The value 5 is assigned to the variable x using the simple assignment operator in the above example.

Compound Assignment Operators (e.g., +=, -=, *=, /=): 

Compound assignment operators combine a binary operator with a simple assignment operator. They perform an operation between the LHS and RHS, and the result is returned to the LHS. 

In the above example, the compound assignment operator += adds 5 to the variable x and returns the result to x.

Compound assignment operators provide a concise way to perform an operation and assign the result in a single statement.

assignment operators in c programming with examples

Table showcasing list of operators in C

Example Programs

Let’s look at some assignment operators' example - 

Example 1: = Operator

Example 2: += operator, example 3: -= operator, example 4: *= operator, example 5: /= operator, example 6: %= operator, example 7: <<= operator, example 8: >>= operator, example 9: &= operator, example 10: |= operator, example 11: ^= operator, working of assignment operators in c.

Let’s understand the working of Assignment Operators in C with the help of a simple table - 

Assignment operators provide various capabilities, from basic assignments to arithmetic, bitwise, and shift operations. Mastering these operators enables programmers to perform complex calculations and transformations with ease. With their concise syntax and powerful functionality, assignment operators function as a fundamental component of C programming, contributing to code readability and maintainability. The best way to hone proficiency and practical knowledge regarding the same is by upskilling, and what could be better than applying on upGrad for this!

Programming aspirants looking to master skills in software development must consider upGrad’s Executive Post Graduate Program in Software Development - Specialisation in Full Stack Development course offered under the supervision of IIIT-B. This PG program with help learners get an insight into exclusive masterclasses on GenAI, computer science fundamentals, the process of software development, building scalable websites, backend APIs, and much more. Be it a new and seasoned software developer, this program is bound to fuel your flight to success!

1. What is the difference between simple and compound assignment operators in C?

The simple assignment operator (=) assigns the value of the right operand to the left operand. The compound assignment operators (+=, -=, etc.) perform an arithmetic operation and assign the result to the left operand.

2. Can I assign the same value to multiple variables using a single assignment statement?

You can assign the same value to multiple variables using the simple assignment operator in a single line of code, such as "x = y = z = 10;".

3. Are there any precedence rules to consider when using compound assignment operators?

Yes, compound assignment operators have lower precedence than most other operators in C. It's important to use parentheses to clarify the order of operations if necessary, especially when combining compound assignment operators with other arithmetic or bitwise operators.

Leave a Reply

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

Suggested Tutorials

Software Key Tutorial

  • by Mukesh kumar
  • 08 Dec 2023

Python Tutorial

  • 17 Nov 2023

Java Tutorial

  • 26 Sep 2023

Subscribe to our newsletter.

  • Login Forgot Password

assignment operators in c programming with examples

  • What Are Operators in C? All Types of C Language Operators With Symbols

Basics of C Language 0 / 9

  • What is C Programming Language? Full Introduction with Features, Benefits, History
  • The History of C Language (Evolution Over Years & All Versions of C Programming)
  • Top 10 Features of C Language (Characteristics of C Programming)
  • How to Download & Install C Programming Software on Windows 10? Step-by-Step Guide
  • Full List of Keywords in C Language (With Examples & Explanation)
  • What Are Identifiers in C Language? Examples, Rules, Types, Tips, Free PDF
  • What Are Variables in C Language? Examples, Rules, Types, Scope, Declaration
  • What Are Constants in C Language? Types, Examples, Rules, How to Use?
  • What Are Data Types in C Language? Definition, Types, Examples, Range, Size

Important Concepts 0 / 4

  • for loop in C Programming (With Examples)
  • while and do while Loops in C (Explained With Examples, Syntax, Flowchart)
  • What is Array in C? Examples, Types, Uses (Full Guide)

Table of Contents

Introduction, what is an operator in c, types of operators in c, operators in c language- video, precedence of operators in c, operator precedence and associativity in c: video.

C is a popular programming language with numerous built-in operators to perform several actions and tasks based on program requirements. An operator in C takes part in a program to manipulate data and perform operations on variables and values. 

These operators are symbols, each representing a specific operation to be performed on operands. They form a part of conditional, mathematical, and logical expressions. 

There is a wide range of operators in the C language; each belongs to a different category according to its functionalities. In this article, we’ll discuss all the C operators in detail, along with examples.

Operators in C are an important feature of this programming language. They are symbols used to perform mathematical, conditional, relational, or logical manipulations. In other words, operators tell the compiler to perform specific operations on operands. 

They operate on variables or values. There are several C language operators that perform almost all operations and can be extremely useful. Without these operators, the functionality of C is incomplete. 

For example,

In m + n, + is an operator to perform addition, and ‘ m ’ and ‘ n ’ are operands. The operator tells the C compiler to add the given operands.

There is a wide range of built-in operators in C that we will discuss in the blog.

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Misc Operator

1. Arithmetic Operators

Arithmetic operations are used for mathematical or arithmetic calculations, such as division (/), addition (+), subtraction (-), multiplication (*), etc., on operands. It performs operations on constants and variables , i.e., numerical values. 

Unary Operators: These operators work with a single operand. For example, increment and decrement operators.

Binary Operators: These operators work with two operands. For example, addition, subtraction, division, and multiplication. 

The following table demonstrates arithmetic operators in C and their functions.

There are increment (++) and decrement (--) operators too, which change the value of an operand by 1. They are extremely useful as they reduce calculation to a minimum. They are unary operators, so include only one operand. 

When we use the pre-fix operator, it adds 1 to the operand and assigns the result to the variable on the left. On the other hand, when the operator is used as a post-fix, it first assigns a value to the left variable and then increases the operand by 1. 

Arithmetic Operators in C- Video

Understand the concept of C arithmetic operators with the below video:

2. Relational Operators

Relational operators in C are used to compare the values of two operands in a program. It evaluates the relationship between the given operands. If the relation is true, it returns 1; else, it returns 0. These operators are often used for decision-making and loop operations. 

For example, checking if one operand is greater or equal to another. Relational operators include ==, >= , <= .

3. Logical Operators

A Logical operator of C language combines and tests two or more conditions to make decisions. In addition, it is used to complement the evaluation of the original condition, which is in consideration. It returns a boolean value as either true or false. 

An expression with logical operators or symbols in C programming returns a 0 or 1 result based on whether the condition is true or false. 

For example, when we use the logical AND operator ‘&&’ in C language, it returns true if both conditions are satisfied; else, it returns false. Only when given two conditions are satisfied in the given expression will it return true.

Video: Logical Operators in C

4. Bitwise Operators

Bitwise operators in C programming language are used to perform bit-level operations on the operands. It first converts mathematical operations, such as subtraction, addition, multiplication, and division, to bit-level and then performs the calculation between operands. 

It makes the implementation process during computation and program compiling faster and easier. For example, the bitwise operator in C ‘&’ takes two values as operands and performs AND on every bit of the two values. The result is 1 only if both bits are true, i.e., 1.

Bitwise Operators in C Programming- Video

Learn in simple terms with our video on Bitwise operators in C language:

5. Assignment Operators

Assignment operators in C assign a value to a variable. The left operand of this operator is called a variable, and the right operand is known as the value. The variable on the left side and the value on the right side must have the same data type; else the compiler will show an error. The most common assignment operator is =. 

Video: Assignment Operator in C Programming

6. Miscellaneous Operators in C

Besides the operators mentioned above in C, some more operators are used to carry out different tasks. Let’s have a look at them:

sizeof Operator

sizeof is a compile-binary unary operator in C language used to compute the size of operands. Its result is an unsigned internal type denoted by size_t. 

Comma Operator

The comma operator in C is represented by the token. It is a binary operator with the lowest precedence among all C operators. It works as an operator and separator. It evaluates the first operand, discards the result, evaluates the second operand, and returns its value. 

Conditional Operator

It is written in the form of Expression1? Expression2: Expression3. Expression 1 is the condition that needs to be evaluated, and if it is true, then Expression 2 is executed, and we return the result. 

However, if Expression 1 is false, we execute and return the result of Expression 3. We can use conditional operators to replace if…else statements. 

dot (.) and arrow (->) Operators

They are member operators used to reference individual members of classes, unions, and structures. The dot (.) operator is applied to real objects, while the arrow operator (->) is used with a pointer. 

Cast Operator 

It converts one type of data to another type. This special C operator forces one data type to convert into another. 

&,* Operator

& returns a variable’s address while * operator is a pointer to a variable. For example, &a; will give the address of the variable, and *var will be a pointer to a variable ‘var.

Here is a detailed video on C language operators, explaining everything in simple terms:

Operator precedence is a crucial feature of C programming that groups terms in an expression and then decides the way the expression is evaluated based on the provided expression. Some operators in C have high precedence than others, while some have lower precedence. It decreases from top to bottom.

The following table shows the precedence and associativity of operators in C. 

Learn in detail about Operator Precedence and Associativity in C Programming with a video:

  • C - Introduction
  • C - Comments
  • C - Data Types
  • C - Type Casting
  • C - Operators
  • C - Strings
  • C - Booleans
  • C - If Else
  • C - While Loop
  • C - For Loop
  • C - goto Statement
  • C - Continue Statement
  • C - Break Statement
  • C - Functions
  • C - Scope of Variables
  • C - Pointers
  • C - Typedef
  • C - Format Specifiers
  • C Standard Library
  • C - Data Structures
  • C - Examples
  • C - Interview Questions

AlphaCodingSkills

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

C - Bitwise OR and assignment operator

The Bitwise OR and assignment operator (|=) assigns the first operand a value equal to the result of Bitwise OR operation of two operands.

(x |= y) is equivalent to (x = x | y)

The Bitwise OR operator (|) is a binary operator which takes two bit patterns of equal length and performs the logical OR operation on each pair of corresponding bits. It returns 1 if either or both bits at the same position are 1, else returns 0.

The example below describes how bitwise OR operator works:

The code of using Bitwise OR operator (|) is given below:

The output of the above code will be:

Example: Find largest power of 2 less than or equal to given number

Consider an integer 1000. In the bit-wise format, it can be written as 1111101000. However, all bits are not written here. A complete representation will be 32 bit representation as given below:

Performing N |= (N>>i) operation, where i = 1, 2, 4, 8, 16 will change all right side bit to 1. When applied on 1000, the result in 32 bit representation is given below:

Adding one to this result and then right shifting the result by one place will give largest power of 2 less than or equal to 1000.

The below code will calculate the largest power of 2 less than or equal to given number.

The above code will give the following output:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial
  • Standard Template Library
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators

Related Articles

  • Solve Coding Problems
  • C++ Map - Erasing Elements By Callback
  • How to Iterate a STL Queue in C++?
  • Vector of Maps in C++ with Examples
  • C++ Map of Functions
  • Inserting elements in std::map (insert, emplace and operator [])
  • map::size() in C++ STL
  • How to Use Binder and Bind2nd Functors in C++ STL?
  • Different Ways to Initialize a Map in C++
  • C++ Program to Implement strpbrk() Function
  • Map and External Sorting Criteria/Comparator in C++ STL
  • Convert Octal String to Integer using stoi() Function in C++ STL
  • Passing Map as Reference in C++ STL
  • map::begin() and end() in C++ STL
  • Shuffle an Array using STL in C++
  • How to insert data in the map of strings?
  • map::empty() in C++ STL
  • map::clear() in C++ STL
  • Binders in C++ STL
  • How to find the Entry with largest Value in a C++ Map

How to Add Elements to a Map in C++?

In C++, a map is an associative container that stores the elements as key-value pairs where each element has a key and a mapped value. In this article, we will learn how to add elements to a map in C++ STL.

For Example,

Add Elements into a Map in C++

To insert a key-value pair in a std::map , we can use the array subscript operator [] with the key inside the brackets and assign it the required value using the assignment operator. If the key already exists, then its value will be updated. Otherwise, the new elements will be added

C++ Program to Add Key-Value Pair into a Map

The below example demonstrates how we use insert() function to add key-value pair into a map in C++ STL .

Time Complexity: O(m log n), where n is the number of elements in the map, and m is the number of elements to be inserted. Auxiliary Space: O(m)

Note: We can also use map::insert() ethod to add key-value pairs in a map in C++.

Please Login to comment...

author

  • CPP Examples
  • C++ Programs

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Assignment Operators in C

    assignment operators in c programming with examples

  2. Operators In C Logicmojo

    assignment operators in c programming with examples

  3. Operators in C Programming

    assignment operators in c programming with examples

  4. Operators in C

    assignment operators in c programming with examples

  5. C Programming Tutorial

    assignment operators in c programming with examples

  6. C programming +=

    assignment operators in c programming with examples

VIDEO

  1. Working with Assignment operators in C| C Tutorials for Beginners

  2. Operators in C language

  3. Lecture 15||Relational Operators||C programming Tutorials||Complete Playlist||Placements||

  4. Functions in C Programming

  5. Lecture 5 Part II Operators in C++ || Programming Fundamentals

  6. Assignment Operators

COMMENTS

  1. Assignment Operators in C

    Example: (a *= b) can be written as (a = a * b) 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:

  2. Assignment Operators in C

    Assignment Operators in C The following table lists the assignment operators supported by the C language − Example Try the following example to understand all the assignment operators available in C − Live Demo

  3. Assignment Operators in C Example

    The Assignment operators in C are some of the Programming operators that are useful for assigning the values to the declared variables. Equals (=) operator is the most commonly used assignment operator. For example: int i = 10; The below table displays all the assignment operators present in C Programming with an example.

  4. Operators in C

    Run Code Output ++a = 11 --b = 99 ++c = 11.500000 --d = 99.500000 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

  5. Assignment Operators in C with Examples

    Assignment Operators in C with Examples By Chaitanya Singh | Filed Under: c-programming Assignment operators are used to assign value to a variable. The left side of an assignment operator is a variable and on the right side, there is a value, variable, or an expression.

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

    2 1. Simple Assignment Operator In C 2.1 Syntax 2.2 Example -: 3 2. Compound Assignment Operators In C 3.1 Syntax of Compound Assignment Operators 3.2 Example -: 4 List of Assignment Operators In C 5 Conclusion Assignment Operators In C

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

  8. Assignment Operators in C

    1000 5 Start Learning 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.

  9. Assignment and shorthand assignment operator in C

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

  10. Assignment Operator in C

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

  11. C Operators

    In C programming, assignment operators are used to assign a value to a variable. The most commonly used assignment operator is the = operator, but there are also other assignment operators that perform arithmetic or bitwise operations in conjunction with assignment. These operators include: The assignment operators in C programming include:

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

  13. C Operators

    Assignment operators are used to assign values to variables. In the example below, we use the assignment operator ( =) to assign the value 10 to a variable called x: Example int x = 10; Try it Yourself » The addition assignment operator ( +=) adds a value to a variable: Example int x = 10; x += 5; Try it Yourself »

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

  15. C Programming Course Notes

    C Programming Course Notes - Operators Introduction to C Programming A full table of precedence and associativity is included in any good book on C Programming. There are also of this information on the web.

  16. Assignment operators in C

    C programming assignment operators; In this tutorial, you will learn about assignment operators in c programming with examples. C Assignment Operators. An assignment operator is used for assigning a value to a variable in c programming language. List of Assignment Operators in C. Note that:- There are 2 categories of assignment operators in C ...

  17. Assignment Operator in C

    C File Handling C fprintf () fscanf () C fputc () fgetc () C fputs () fgets () C fseek () C rewind () C ftell () C Preprocessor C Preprocessor C Macros C #include C #define C #undef C #ifdef C #ifndef C #if C #else C #error C #pragma C Preprocessor Test C Command Line

  18. Operators in C

    There are 9 arithmetic operators in C language: Example of C Arithmetic Operators C #include <stdio.h> int main () { int a = 25, b = 5; printf("a + b = %d\n", a + b); printf("a - b = %d\n", a - b); printf("a * b = %d\n", a * b); printf("a / b = %d\n", a / b); printf("a % b = %d\n", a % b);

  19. Discovering C Operators: An Overview with Types and Examples!

    x = (y = (10)); This shows that assignment operators are binary operators, requiring two operands. The LHS operand must be a variable, and the RHS operand can be a constant, variable, or expression. Left Operand = Right Operand List of All Assignment Operators in C

  20. Operators in C Language (Explained All Types With Symbols)

    Assignment Operators. ... An expression with logical operators or symbols in C programming returns a 0 or 1 result based on whether the condition is true or false. ... For example, the bitwise operator in C '&' takes two values as operands and performs AND on every bit of the two values. The result is 1 only if both bits are true, i.e., 1.

  21. C Bitwise OR and assignment operator

    The Bitwise OR and assignment operator (|=) assigns the first operand a value equal to the result of Bitwise OR operation of two operands. (x |= y) is equivalent to (x = x | y) The Bitwise OR operator (|) is a binary operator which takes two bit patterns of equal length and performs the logical OR operation on each pair of corresponding bits.

  22. Operators in C Programming: Types, Precedence and Examples

    In 'C' programming language, there are various types of operators. Unary Operators: These operators require only one operand. increment and decrement operators. Binary Operators: These operators require two operands. arithmetic operators, relational operators, logical operators, bitwise operators, assignment operators, Ternary Operators ...

  23. 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 ( |= )

  24. How to Add Elements to a Map in C++?

    To insert a key-value pair in a std::map, we can use the array subscript operator [] with the key inside the brackets and assign it the required value using the assignment operator. If the key already exists, then its value will be updated. Otherwise, the new elements will be added C++ Program to Add Key-Value Pair into a Map