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 Data Types

C operators.

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

C File Handling

  • C Cheatsheet

C Interview Questions

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

C Variables and Constants

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

C Input/Output

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

Assignment Operators in C

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

C Control Statements Decision-Making

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

C Arrays & Strings

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

C User-Defined Data Types

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

C Storage Classes

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

C Memory Management

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

C Preprocessor

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

Miscellaneous

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

advantages of shorthand assignment operator in c

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

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example:

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

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

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

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

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

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

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

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

Below example illustrates the various Assignment Operators:

Please Login to comment...

Similar reads.

  • C-Operators
  • cpp-operator

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Library homepage

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

selected template will load here

This action is not available.

Engineering LibreTexts

4.4: Arithmetic Assignment Operators

  • Last updated
  • Save as PDF
  • Page ID 11256

  • Kenneth Leroy Busbee
  • Houston Community College via OpenStax CNX

Overview of Arithmetic Assignment

The five  arithmetic assignment  operators are a form of short hand. Various textbooks call them "compound assignment operators" or "combined assignment operators". Their usage can be explaned in terms of the assignment operator and the arithmetic operators. In the table we will use the variable age and you can assume that it is of integer data type.

Demonstration Program in C++    

Creating a folder of sub-folder for source code files.

Depending on your compiler/IDE, you should decide where to download and store source code files for processing. Prudence dictates that you create these folders as needed prior to downloading source code files. A suggested sub-folder for the  Bloodshed Dev-C++ 5 compiler/IDE  might be named:

  • Demo_Programs

If you have not done so, please create the folder(s) and/or sub-folder(s) as appropriate.

Download the Demo Program

Download and store the following file(s) to your storage device in the appropriate folder(s). Following the methods of your compiler/IDE, compile and run the program(s). Study the soruce code file(s) in conjunction with other learning materials.

Download from Connexions:  Demo_Arithmetic_Assignment.cpp

Jumptuck Logo

C Programming Language: shorthand

Mike Szczys

Shorthand in C is extremely simple. Any time you are assigning a value of a variable that uses that variable in the assignment you can simplify the syntax. For example:

This line of code adds 32 to the current value of ‘myVar’. But you don’t need to type ‘myVar’ twice. Instead, move the operator (that’s the plus sign in this case) to the left side of the assignment operator (the equals sign). The portion of code originally on right side of the operator will be the only thing still remaining on the right side of the assignment operator in our shortened code snippet:

This will work for any type of operator, and for any complexity of assignment as long as you can get the variable alone on the left side of the argument.

If you want to use a bitwise operator on a variable:

It can be used by the shifting operators as well:

If you weren’t already familiar with this, it should make it much easier to read other developers’ code since shorthand is almost always used when it can be. It will also increase your coding speed, and decrease you hand and wrist pain!

Next: Execution Control Expressions , Previous: Arithmetic , Up: Top   [ Contents ][ Index ]

7 Assignment Expressions

As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues ) because they are locations that hold a value.

An assignment in C is an expression because it has a value; we call it an assignment expression . A simple assignment looks like

We say it assigns the value of the expression value-to-store to the location lvalue , or that it stores value-to-store there. You can think of the “l” in “lvalue” as standing for “left,” since that’s what you put on the left side of the assignment operator.

However, that’s not the only way to use an lvalue, and not all lvalues can be assigned to. To use the lvalue in the left side of an assignment, it has to be modifiable . In C, that means it was not declared with the type qualifier const (see const ).

The value of the assignment expression is that of lvalue after the new value is stored in it. This means you can use an assignment inside other expressions. Assignment operators are right-associative so that

is equivalent to

This is the only useful way for them to associate; the other way,

would be invalid since an assignment expression such as x = y is not valid as an lvalue.

Warning: Write parentheses around an assignment if you nest it inside another expression, unless that is a conditional expression, or comma-separated series, or another assignment.

Shorthand Operator in C

Shorthand Operator in C – C has a special operator called  shorthand  that simplifies coding a certain type of assignment statements.

Example for Shorthand Operator in C

a = a+2;  can be written as:  a += 2;

The operator += tells the compiler that a is assigned the value of a + 2;

This shorthand works for all binary operators in C.

The general form is   variable operator = variable / constant / expression

These operators are listed below:

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related Posts

  • #define to implement constants
  • Preprocessor in C Language
  • Pointers and Strings

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.

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

advantages of shorthand assignment operator in c

  • Learn C Programming

Introduction

  •  Historical Development of C
  •  Importance of C
  •  Basic Structure of C Program
  •  Executing a C Program
  •  Compiler, Assembler, and Interpreter

Problem Solving Using Computer

  • Problem Analysis
  •  Types of Errors
  •  Debugging, Testing, and Program Documentation
  •  Setting up C Programming Environment

C Fundamentals

  •  Character Set
  •  Identifiers and Keywords
  •  Data Types
  •  Constants and Variables
  •  Variable/Constant Declaration
  •  Pre-processor Directive
  •  Symbolic Constant

C Operators and Expressions

  • Operators and Types
  •  Arithmetic Operators
  •  Relational Operators
  •  Logical Operators
  •  Assignment Operators
  •  Conditional Operator
  •  Increment and Decrement Operators
  •  Bitwise Operators
  •  Special Operators
  •  Precedence and Associativity

C Input and Output

  • Input and Output functions
  • Unformatted I/O
  •  Formatted I/O

C Decision-making Statements

  • Decision-making Statements in C
  •  Nested if else
  •  Else-if ladder
  •  Switch Case
  •  Loop Control Statements in C

C Functions

  •  Get Started
  •  First Program

advantages of shorthand assignment operator in c

Assignment Operators in C

Assignment operators are used to assigning the result of an expression to a variable. Up to now, we have used the shorthand assignment operator “=”, which assigns the result of a right-hand expression to the left-hand variable. For example, in the expression x = y + z, the sum of y and z is assigned to x.

Another form of assignment operator is variable operator_symbol= expression ; which is equivalent to variable = variable operator_symbol expression;

We have the following different types of assignment and assignment short-hand operators.

Expected Output:

  • Shorthand Operators

Assignment Operators are used for assigning values to the variables in the program. There are two types of Assignment operators used. The first one being the Simple Assignment Operator and the other one being Shorthand Operators or Compound Assignment Operators. Expressions or Values can be assigned to the variable using Shorthand Assignment Operators. C++ supports both types of Assignment Operators. Let us look at the Shorthand Assignment Operators and their different types in this article below.

Shorthand Operators

  • Shorthand Assignment Operators combines one of the arithmetic or bitwise operators with the assignment operator. They are also called as compound assignment operators.
  • A Shorthand Assignment Operator is a shorter way of expressing something that is already available in the programming statements.

C++ language offers its users a few special shorthand’s that simplifies the coding of certain expressions. It also saves coding time by using these Shorthand Operators in the program. Shorthand Assignment Operators have the lowest order of precedence i.e., they are the last to be evaluated in an expression.

Shorthand Assignment Operators follow the following Syntax –

variable_name operator = expression/value ;

which is equivalent to :

variable_name = variable_name operator expression/value ;  

Note:  The variable data type and the value assigned to it should match. Or else the compiler will give an error while running the program.

Browse all the Topics Under Operator and Expressions: Operators

  • Arithmetic Operators
  • Assignment Operator s
  • Unary Operator
  • Increment and Decrement Operators
  • Relation Operator
  • Logical Operators

Types of Shorthand Assignment Operators

Shorthand Assignment Operators are Binary Operators which require 2 values or 1 variable and another value/expression. One on the left and the other on the right side.

The following are types of Shorthand Assignment Operators

This type of Operator is a combination of Arithmetic Operator ‘+’ and Assignment Operator ‘=’. This operator adds the variable on the left with the value on the right and then assigns/saves the result to the variable on the left.

These types of Shorthand Operators are used with a combination of Subtraction Arithmetic Operator ‘-‘ and Assignment operator ‘=’.

These Shorthand Operators use a combination of Multiplication type of Arithmetic Operator ‘*’ and Simple Assignment operator ‘=‘. The variable to the left is multiplied with the value or expression to the right side and then the result is stored into the variable defined to the left.

Here, a combination of Division Arithmetic operator ‘/’ and Simple Assignment Operator ‘=’ is seen. The variable is divided by the value first and then the value is stored to the left, in the variable.

This type of operator uses Modulus Operator ‘%’ and an Assignment Operator ‘=’ in its syntax. It returns the Remainder of the two operands and stores the value in the variable to the left side of the statement.

Apart from the Assignment Operators, the Shorthand Operators are also used to define the Bitwise Operators.

Some of them are:

FAQs on Shorthand Operators

Q1. Which of the following is a valid assignment operator?

  • All of the Above

Answer. Option D

Q2. What does the *= assignment operator do?

  • Multiplies the value twice
  • Multiplies variable with value once
  • Used as exponent like 2*3 = 8
  • None of the Above

Answer. Option B

Q3. Do the given two equations mean the same?

count += 1 ;

count = count + 1 ;

Answer. Option A

Q4. What is the final output of variable ‘a’ in the below program?

Answer. Option C.

Customize your course in 30 seconds

Which class are you in.

tutor

Operator and Expressions: Operators

  • Assignment Operators
  • Unary Operators
  • Increment & Decrement Operators
  • Relational Operators

Leave a Reply Cancel reply

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

Download the App

Google Play

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

2 - Types, Operators, and Expressions

Variables and constants are the basic data objects manipulated in a program. Declarations list the variables to be used, and state what type they have and perhaps what their initial values are. Operators specify what is to be done to them. Expressions combine variables and constants to produce new values. These are the topics of this chapter.

2.1 - Variable Names ​

Although we didn't come right out and say so, there are some restrictions on variable and symbolic constant names. Names are made up of letters and digits; the first character must be a letter. The underscore "_" counts as a letter; it is useful for improving the readability of long variable names. Upper and lower case are different; traditional C practice is to use lower case for variable names, and all upper case for symbolic constants.

Only the first eight characters of an internal name are significant, although more may be used. For external names such as function names and external variables, the number may be less than eight, because external names are used by various assemblers and loaders. Appendix A lists details. Furthermore, keywords like if , else , int , float , etc., are reserved : you can't use them as variable names. (They must be in lower case.)

In modern C languages, the limitation of the first eight characters of a variable name being unique has been extended. In most C variants you can expect that at least 30 characters of a variable name are treated as unique. The eight character limitation was to reflect a typical limitation of identifier length in assembly language programming and run-time linkers of the time.

Naturally it's wise to choose variable names that mean something, that are related to the purpose of the variable, and that are unlikely to get mixed up typographically.

2.2 - Data Types and Sizes ​

There are only a few basic data types in C:

In addition, there are a number of qualifiers which can be applied to int : short , long , and unsigned . short and long refer to different sizes of integers, unsigned numbers obey the laws of arithmetic modulo 2 n 2^n 2 n , where n is the number of bits in an int ; unsigned numbers are always positive. The declarations for the qualifiers look like

The word int can be omitted in such situations, and typically is.

The precision of these objects depends on the machine at hand; the table below shows some representative values.

The intent is that short and long should provide different lengths of integers where practical; int will normally reflect the most "natural" size for a particular machine. As you can see, each compiler is free to interpret short and long as appropriate for its own hardware. About all you should count on is that short is no longer than long .

In the mid 1970's, C was designed to support a range of computer generations. The PDP-11 was a common "previous-generation" computer that has less memory and so variable sizes were kept small. The more modern computers in this chart had a bit more memory and so could afford to have slightly larger sizes.

The idea of "natural" size is the size that could be loaded, computed, and stored in a single machine language instruction. You knew as a programmer that when you used int , the machine code generated from your program would not need to include extra instructions for a simple line of code like x = x + 1; .

Modern int values in C are 32-bits long and long values are 64-bits long. Even though modern computers can do 64-bit computations in a single instruction, using the shorter int type when appropriate can save on memory storage and memory bandwidth when using int values.

Interestingly the length of a 32-bit int leads to a UNIX/C problem with dates that is called the "Year 2038 Problem". A common way to represent time in UNIX/C programs was as a 32-bit integer in the number of seconds since 1-Jan-1970. It was quick and easy to compare, add or subtract these second counter dates in code and databases. But the number of seconds since 1-Jan-1970 will overflow a 32-bit number on 19-Jan-2038. By now, in order to avoid problems most systems have converted to storing these "number of seconds" values in long (64-bit) values. Which gives us almost 300 billion years until we need to worry about overflowing timer counters again.

Back when C was developed we had two different character sets and two different char variable lengths. The world generally standardized on the ASCII character set for the core western characters and Unicode / UTF-8 to represent all characters in all languages worldwide. But that is a story for another time. For now, just think of the char type as also a byte type, is 8-bits in length and can store ASCII. Modern languages like Python or Java have excellent support for wide character sets. In our historical look at C - we will not cover wide or multi-byte characters.

Also if you look at the float and double types, you see different bit-sizes. Even worse, each of these computers did floating point computation using slightly different hardware implementations and the same code run on different computers would give slightly different results and have unpredictable behavior on overflow, underflow and other extraordinary floating point operations. This was solved by the introduction of the IEEE 754 (1985) floating point format standard - which standardized both the length of float and double but insured that the same set of floating point calculations would produce the exact same result on different processors.

2.3 - Constants ​

int and float constants have already been disposed of, except to note that the usual

"scientific" notation for float 's is also legal. Every floating point constant is taken to be double , so the "e" notation serves for both float and double .

Long constants are written in the style 123L . An ordinary integer constant that is too long to fit in an int is also taken to be a long .

There is a notation for octal and hexadecimal constants: a leading 0 (zero) on an int constant implies octal; a leading 0x or 0X indicates hexadecimal. For example, decimal 31 can be written as 037 in octal and 0x1f or 0X1F in hex. Hexadecimal and octal constants may also be followed by L to make them long .

A character constant is a single character written within single quotes, as in 'x' . The value of a character constant is the numeric value of the character in the machine's character set. For example, in the ASCII character set the character zero, or '0' , is 48, and in EBCDIC '0' is 240, both quite different from the numeric value 0. Writing '0' instead of a numeric value like 48 or 240 makes the program independent of the particular value. Character constants participate in numeric operations just as any other numbers, although they are most often used in comparisons with other characters. A later section treats conversion rules.

Certain non-graphic characters can be represented in character constants by escape sequences like \n (newline), \t (tab), \0 (null), \\ (backslash), \' (single quote), etc., which look like two characters, but are actually only one. In addition, an arbitrary byte-sized bit pattern can be generated by writing

where ddd is one to three octal digits, as in

In the 1970's we sent much of our output to printers. A "form feed" was the character we would send to the printer to advance to the top of a new page.

The character constant '\0' represents the character with value zero.

'\0' is often written instead of 0 to emphasize the character nature of some expression.

A constant expression is an expression that involves only constants. Such expressions are evaluated at compile time, rather than run time, and accordingly may be used in any place that a constant may be, as in

A string constant is a sequence of zero or more characters surrounded by double quotes, as in

The quotes are not part of the string, but serve only to delimit it. The same escape sequences used for character constants apply in strings; \" represents the double quote character.

Technically, a string is an array whose elements are single characters. The compiler automatically places the null character \0 at the end of each such string, so programs can conveniently find the end. This representation means that there is no real limit to how long a string can be, but programs have to scan one completely to determine its length. The physical storage required is one more location than the number of characters written between the quotes. The following function strlen(s) returns the length of a character string s , excluding the terminal \0 .

Be careful to distinguish between a character constant and a string that contains a single character: 'x' is not the same as "x" . The former is a single character, used to produce the numeric value of the letter x in the machine's character set. The latter is a character string that contains one character (the letter x ) and a \0 .

2.4 - Declarations ​

All variables must be declared before use, although certain declarations can be made implicitly by context. A declaration specifies a type, and is followed by a list of one or more variables of that type, as in

Variables can be distributed among declarations in any fashion; the lists above could equally well be written as

This latter form takes more room, but is convenient for adding a comment to each declaration or for subsequent modifications.

Variables may also be initialized in their declaration, although there are some restrictions. If the name is followed by an equals sign and a constant, that serves as an initializer, as in

If the variable in question is external or static, the initialization is done once only, conceptually before the program starts executing. Explicitly initialized automatic variables are initialized each time the function they are in is called. Automatic variables for which there is no explicit initializer have undefined (i.e., garbage) values. External and static variables are initialized to zero by default, but it is good style to state the initialization anyway.

We will discuss initialization further as new data types are introduced.

2.5 - Arithmetic Operators ​

The binary arithmetic operators are + , - , * , / , and the modulus operator % . There is a unary - , but no unary + .

Integer division truncates any fractional part. The expression

produces the remainder when x is divided by y , and thus is zero when y divides x exactly. For example, a year is a leap year if it is divisible by 4 but not by 100, except that years divisible by 400 are leap years. Therefore

The % operator cannot be applied to float or double .

The + and - operators have the same precedence, which is lower than the (identical) precedence of * , / , and % , which are in turn lower than unary minus. Arithmetic operators group left to right. (A table at the end of this chapter summarizes precedence and associativity for all operators.)

The order of evaluation is not specified for associative and commutative operators like * and + ; the compiler may rearrange a parenthesized computation involving one of these. Thus a+(b+c) can be evaluated as (a+b)+c . This rarely makes any difference, but if a particular order is required, explicit temporary variables must be used.

The action taken on overflow or underflow depends on the machine at hand.

The above paragraph allowing the compiler to reorder computations even in the presense of parenthesis is known as the "K&R C Rearrangement License". As the author's state, it almost never makes a difference unless an expression contains a value computed in a function call or there is a pointer lookup to find a value for the computation that might fail. This rule was subtly adjusted in the ISO version of C but ISO C still does does not strictly force the order of otherwise commutative operations - even in the presense of parenthesis.

The good news is that as long as you keep your expressions simple, you don't have to worry about this rule. Sometimes the real value of parenthesis is to communicate your intentions to human readers of your code. If you are writing code that depends of the order of overflow, function calls, and pointer dereferences in a single mathematical expression - perhaps you should break your expression into multiple statements.

2.6 - Relational and Logical Operators ​

The relational operators are

They all have the same precedence. Just below them in precedence are the equality operators:

which have the same precedence. Relationals have lower precedence than arithmetic operators, so expressions like i < lim-1 are taken as i < (lim - 1) , as would be expected.

More interesting are the logical connectives && and || . Expressions connected by && or || are evaluated left to right, and evaluation stops as soon as the truth or falsehood of the result is known. These properties are critical to writing programs that work. For example, here is a loop from the input function getline which we wrote in Chapter 1 .

Clearly, before reading a new character it is necessary to check that there is room to store it in the array s , so the test i<lim-1 must be made first. Not only that, but if this test fails, we must not go on and read another character.

Similarly, it would be unfortunate if c were tested against EOF before getchar was called: the call must occur before the character in c is tested.

The precedence of && is greater than that of || , and both are lower than relational and equality operators, so expressions like

need no extra parentheses. But since the precedence of != is higher than assignment, parentheses are needed in

to achieve the desired result.

One of the great debates of the 1970's was how to use Structured Programming to avoid any use of "goto" statements that lead to completely unreadable "spaghetti code". Structured code was easier to read, debug, and validate. Structured Programming advocated for if-then-else, else if, while-do loops and do-while loops where the loop exit test was at the top or bottom of loops respectively.

There was a move from Flow Charts with lines, boxes and arrows to structured diagramming techniques like Nassi–Shneiderman diagrams that used nested boxes to emphasize the structured nature of the code.

The proponents of each approach tended to approach the problem based on the language they used. ALGOL and PASCAL programmers were strong advocates of structured programming and those languages had syntax that encouraged the approach. FORTRAN programmers had decades of flow-chart style thinking and tended to eschew full adoption of structured programming.

Kernighan and Ritchie chose a "middle path" and made it so C could support both approaches to avoid angering either side of the structured programming debate.

One area where the "structured programming" movement kept hitting a snag was implementing a loop that reads a file and processes data until it reaches the end of file. The loop must be able to handle an empty file or no data at all. There are three ways to construct a "read and process until EOF" loop and none of the approaches are ideal.

The loop constructions are "top tested loop with priming read before the loop", "bottom tested loop with a read as the first statement in the loop and an if-then-else as the rest of the body of the loop", "top tested infinite loop with a priming read and middle test/exit", and "top tested loop with a side effect read in the test of the loop" (which is the way that Kernighan and Ritchie chose to document in this chapter).

All of this serves to explain the syntax:

This construct is a top-tested loop (which most programmers prefer) and it folds the "priming read" and put its value into the variable c . But since the getchar call might also return EOF we need to check if we actually received no data at all and need to avoid executing the body of the loop or exit the loop.

If EOF were defined as zero instead of -1 , the loop could have been written:

Now the getchar function returns a character or zero and the test itself is looking at the side-effect / residual value of the assignment statement to decide to start and/or continue the loop body. The problem with using zero as EOF if you are reading binary (i.e. like a JPG image) data, a zero character might make perfect sense and we would not want to incorrectly end the loop because of a zero character in the input data that is not end of file.

So we get the double parenthesis, side effect call to getchar and test of the return value inside the while test.

I am quite confident that this is far more detail that you wanted here in Chapter 2, but it is as good a time as any to understand that how much thought goes into how a programming language is designed and documented. By the time we finish Chapter 3 and look at the break and continue statements which are in languages like Python and Java, you will see that this 50-year-old structured programming debate is still unresolved in the minds of many software developers.

The unary negation operator ! converts a non-zero or true operand into 0, and a zero or false operand into 1. A common use of ! is in constructions like

rather than

It's hard to generalize about which form is better. Constructions like !inword read quite nicely ("if not in word"), but more complicated ones can be hard to understand.

Exercise 2-1. Write a loop equivalent to the for loop above without using && .

2.7 - Type Conversions ​

When operands of different types appear in expressions, they are converted to a common type according to a small number of rules. In general, the only conversions that happen automatically are those that make sense, such as converting an integer to floating point in an expression like f + i . Expressions that don't make sense, like using a float as a subscript, are disallowed.

First, char 's and int 's may be freely intermixed in arithmetic expressions: every char in an expression is automatically converted to an int . This permits considerable flexibility in certain kinds of character transformations. One is exemplified by the function atoi , which converts a string of digits into its numeric equivalent.

As we discussed in Chapter 1 , the expression

gives the numeric value of the character stored in s[i] because the values of '0' , '1' , etc., form a contiguous increasing positive sequence.

Another example of char to int conversion is the function lower which maps a single character to lower case for the ASCII character set only. If the character is not an upper case letter, lower returns it unchanged.

This works for ASCII because corresponding upper case and lower case letters are a fixed distance apart as numeric values and each alphabet is contiguous - there is nothing but letters between A and Z . This latter observation is not true of the EBCDIC character set (IBM 360/370), so this code fails on such systems - it converts more than letters.

There is one subtle point about the conversion of characters to integers. The language does not specify whether variables of type char are signed or unsigned quantities. When a char is converted to an int , can it ever produce a negative integer? Unfortunately, this varies from machine to machine, reflecting differences in architecture. On some machines (PDP-11, for instance), a char whose leftmost bit is 1 will be converted to a negative integer ("sign extension"). On others, a char is promoted to an int by adding zeros at the left end, and thus is always positive.

The definition of C guarantees that any character in the machine's standard character set will never be negative, so these characters may be used freely in expressions as positive quantities. But arbitrary bit patterns stored in character variables may appear to be negative on some machines, yet positive on others.

The most common occurrence of this situation is when the value -1 is used for EOF . Consider the code

On a machine which does not do sign extension, c is always positive because it is a char , yet EOF is negative. As a result, the test always fails. To avoid this, we have been careful to use int instead of char for any variable which holds a value returned by getchar .

The real reason for using int instead of char is not related to any questions of possible sign extension. It is simply that getchar must return all possible characters (so that it can be used to read arbitrary input) and, in addition, a distinct EOF value. Thus its value cannot be represented as a char , but must instead be stored as an int .

Since the book was written before the getchar function was standardized, the text is somewhat vague in this section. Shortly after the book was published, getchar was put into the stdio.h and declared to return an integer so as to accommodate all possible characters and the integer -1 value to indicate end of file.

The above code would be better written with c as an integer:

While the conversion from char to int may or may not have sign extension (and yes it still depends on the implementation 50 years later), the conversion from int to char is predictable with the top bits simply being discarded.

If you are using the library function gets to read a file line-by-line, we don't need to worry about this conversion. Since gets returns a pointer to a character array (i.e. a string) - it indicates it has reached end-of-file by returning a "null" pointer (i.e. there is no more data to give).

Another useful form of automatic type conversion is that relational expressions like i > j and logical expressions connected by && and || are defined to have value 1 if true, and 0 if false. Thus the assignment

sets isdigit to 1 if c is a digit, and to 0 if not. (In the test part of if , while , for , etc., "true" just means "non-zero.")

Implicit arithmetic conversions work much as expected. In general, if an operator like + or * which takes two operands (a "binary operator") has operands of different types, the "lower" type is promoted to the "higher" type before the operation proceeds. The result is of the higher type. More precisely, for each arithmetic operator, the following sequence of conversion rules is applied.

  • char and short are converted to int , and float is converted to double .
  • Then if either operand is double , the other is converted to double , and the result is double .
  • Otherwise if either operand is long , the other is converted to long , and the result is long .
  • Otherwise if either operand is unsigned , the other is converted to unsigned , and the result is unsigned .
  • Otherwise the operands must be int , and the result is int .

Notice that all float values in an expression are converted to double ; all floating point arithmetic in C is done in double precision.

Conversions take place across assignments; the value of the right side is converted to the type of the left, which is the type of the result. A character is converted to an integer, either by sign extension or not, as described above. The reverse operation, int to char , is well-behaved - excess high-order bits are simply discarded. Thus in

the value of c is unchanged. This is true whether or not sign extension is involved.

If x is float and i is int , then

both cause conversions; float to int causes truncation of any fractional part. double is converted to float by rounding. Longer int 's are converted to shorter ones or to char 's by dropping the excess high-order bits.

Since a function argument is an expression, type conversions also take place when arguments are passed to functions: in particular, char and short become int , and float becomes double . This is why we have declared function arguments to be int and double even when the function is called with char and float .

Finally, explicit type conversions can be forced ("coerced") in any expression with a construct called a cast . In the construction

the expression is converted to the named type by the conversion rules above. The precise meaning of a cast is in fact as if expression were assigned to a variable of the specified type, which is then used in place of the whole construction. For example, the library routine sqrt expects a double argument, and will produce nonsense if inadvertently handed something else. So if n is an integer,

converts n to double before passing it to sqrt . (Note that the cast produces the value of n in the proper type; the actual content of n is not altered.) The cast operator has the same precedence as other unary operators, as summarized in the table at the end of this chapter.

Exercise 2-2. Write the function htoi(s) , which converts a string of hexadecimal digits into its equivalent integer value. The allowable digits are 0 through 9 , a through f , and A through F .

2.8 - Increment and Decrement Operators ​

C provides two unusual operators for incrementing and decrementing variables. The increment operator ++ adds 1 to its operand; the decrement operator -- subtracts 1. We have frequently used ++ to increment variables, as in

The unusual aspect is that ++ and -- may be used either as prefix operators (before the variable, as in ++n ), or postfix (after the variable: n++ ). In both cases, the effect is to increment n . But the expression ++n increments n before using its value, while n++ increments n after its value has been used. This means that in a context where the value is being used, not just the effect, ++n and n++ are different. If n is 5, then

sets x to 5, but

sets x to 6. In both cases, n becomes 6. The increment and decrement operators can only be applied to variables; an expression like x=(i+j)++ is illegal.

In a context where no value is wanted, just the incrementing effect, as in

choose prefix or postfix according to taste. But there are situations where one or the other is specifically called for. For instance, consider the function squeeze(s, c) which removes all occurrences of the character c from the string s .

Each time a non-c occurs, it is copied into the current j position, and only then is j incremented to be ready for the next character. This is exactly equivalent to

Another example of a similar construction comes from the getline function which we wrote in Chapter 1 , where we can replace

by the more compact

As a third example, the function strcat(s, t) concatenates the string t to the end of the string s . strcat assumes that there is enough space in s to hold the combination.

As each character is copied from t to s , the postfix ++ is applied to both i and j to make sure that they are in position for the next pass through the loop.

Exercise 2-3. Write an alternate version of squeeze(s1, s2) which deletes each character in s1 which matches any character in the string s2 .

Exercise 2-4. Write the function any(s1, s2) which returns the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2 .

2.9 - Bitwise Logical Operators ​

C provides a number of operators for bit manipulation; these may not be applied to float or double .

The bitwise AND operator & is often used to mask off some set of bits; for example,

sets to zero all but the low-order 7 bits of n . The bitwise OR operator | is used to turn bits on:

sets to one in x the bits that are set to one in MASK .

You should carefully distinguish the bitwise operators & and | from the logical connectives && and || , which imply left-to-right evaluation of a truth value. For example, if x is 1 and y is 2, then x & y is zero while x && y is one. (Why?)

The shift operators << and >> perform left and right shifts of their left operand by the number of bit positions given by the right operand. Thus x << 2 shifts x left by two positions, filling vacated bits with 0; this is equivalent to multiplication by 4. Right shifting an unsigned quantity fills vacated bits with 0. Right shifting a signed quantity will fill with sign bits ("arithmetic shift") on some machines such as the PDP-11, and with 0-bits ("logical shift") on others.

The unary operator ~ yields the one's complement of an integer; that is, it converts each 1-bit into a 0-bit and vice versa. This operator typically finds use in expressions like

which masks the last six bits of x to zero. Note that x & ~077 is independent of word length, and is thus preferable to, for example, x & 0177700 , which assumes that x is a 16-bit quantity. The portable form involves no extra cost, since ~077 is a constant expression and thus evaluated at compile time.

To illustrate the use of some of the bit operators, consider the function getbits(x, p, n) which returns (right adjusted) the n-bit field of x that begins at position p . We assume that bit position 0 is at the right end and that n and p are sensible positive values. For example, getbits(x, 4, 3) returns the three bits in bit positions 4, 3 and 2, right adjusted.

x >> (p+1-n) moves the desired field to the right end of the word. Declaring the argument x to be unsigned ensures that when it is right-shifted, vacated bits will be filled with zeros, not sign bits, regardless of the machine the program is run on. ~0 is all 1-bits; shifting it left n bit positions with ~0 << n creates a mask with zeros in the rightmost n bits and ones everywhere else; complementing that with ~ makes a mask with ones in the rightmost n bits.

Bitwise operators may seem unnecessary for modern computers, but if you look at the internal structure of TCP/IP packets, values are packed very tightly into the headers in order to save space. C made it possible to write portable TCP/IP implementations on a wide range of hardware architectures.

Bitwise operators also play an important role in encryption, decryption, and checksum calculations. Modern languages like Java and Python support bitwise operators following the same patterns that we established in C so things like TCP/IP and encryption algorithms can also be implemented in these languages.

By defining these operators, it kept software developers from needing to write non-portable assembly language code to implement these low-level features in operating systems and libraries.

Exercise 2-5. Modify getbits to number bits from left to right.

Exercise 2-6. Write a function wordlength() which computes the word length of the host machine, that is, the number of bits in an int . The function should be portable, in the sense that the same source code works on all machines.

Exercise 2-7. Write the function rightrot(n, b) which rotates the integer n to the right by b bit positions.

Exercise 2-8. Write the function invert(x, p, n) which inverts (i.e., changes 1 into 0 and vice versa) the n bits of x that begin at position p , leaving the others unchanged.

2.10 - Assignment Operators and Expressions ​

Expressions such as

in which the left hand side is repeated on the right can be written in the compressed form

using an assignment operator like += .

Most binary operators (operators like + which have a left and right operand) have a corresponding assignment operator op=, where op is one of

If e1 and e2 are expressions, then

is equivalent to

except that e1 is computed only once. Notice the parentheses around e2 :

is actually

As an example, the function bitcount counts the number of 1-bits in its integer argument.

Quite apart from conciseness, assignment operators have the advantage that they correspond better to the way people think. We say "add 2 to i " or "increment i by 2," not "take i , add 2, then put the result back in i ". Thus i += 2 . In addition, for a complicated expression like

the assignment operator makes the code easier to understand, since the reader doesn't have to check painstakingly that two long expressions are indeed the same, or to wonder why they're not. And an assignment operator may even help the compiler to produce more efficient code.

We have already used the fact that the assignment statement has a value and can occur in expressions; the most common example is

Assignments using the other assignment operators ( += , -= , etc.) can also occur in expressions, although it is a less frequent occurrence.

The type of an assignment expression is the type of its left operand.

Exercise 2-9. In a 2's complement number system, x & ( x-1 ) deletes the rightmost 1-bit in x . (Why?) Use this observation to write a faster version of bitcount .

2.11 - Conditional Expressions ​

The statements

of course compute in z the maximum of a and b . The conditional expression, written with the ternary operator "?:" , provides an alternate way to write this and similar constructions. In the expression

the expression e1 is evaluated first. If it is non-zero (true), then the expression e2 is evaluated, and that is the value of the conditional expression. Otherwise e3 is evaluated, and that is the value. Only one of e2 and e3 is evaluated. Thus to set z to the maximum of a and b ,

It should be noted that the conditional expression is indeed an expression, and it can be used just as any other expression. If e2 and e3 are of different types, the type of the result is determined by the conversion rules discussed earlier in this chapter. For example, if f is a float , and n is an int , then the expression

is of type double regardless of whether n is positive or not.

Parentheses are not necessary around the first expression of a conditional expression, since the precedence of ?: is very low, just above assignment. They are advisable anyway, however, since they make the condition part of the expression easier to see.

The conditional expression often leads to succinct code. For example, this loop prints N elements of an array, 10 per line, with each column separated by one blank, and with each line (including the last) terminated by exactly one newline.

A newline is printed after every tenth element, and after the N-th. All other elements are followed by one blank. Although this might look tricky, it's instructive to try to write it without the conditional expression.

Exercise 2-10. Rewrite the function lower , which converts upper case letters to lower case, with a conditional expression instead of if-else .

2.12 - Precedence and Order of Evaluation ​

The table below summarizes the rules for precedence and associativity of all operators, including those which we have not yet discussed. Operators on the same line have the same precedence; rows are in order of decreasing precedence, so, for example, * , / , and % all have the same precedence, which is higher than that of + and - .

The operators -> and . are used to access members of structures; they will be covered in Chapter 6 , along with sizeof (size of an object). Chapter 5 discusses * (indirection) and & (address of).

Note that the precedence of the bitwise logical operators & , ^ and | falls below == and != . This implies that bit-testing expressions like

must be fully parenthesized to give proper results.

As mentioned before, expressions involving one of the associative and commutative operators ( * , + , & , ^ , | ) can be rearranged even when parenthesized. In most cases this makes no difference whatsoever; in situations where it might, explicit temporary variables can be used to force a particular order of evaluation.

C, like most languages, does not specify in what order the operands of an operator are evaluated. For example, in a statement like

f may be evaluated before g or vice versa; thus if either f or g alters an external variable that the other depends on, x can depend on the order of evaluation. Again, intermediate results can be stored in temporary variables to ensure a particular sequence.

Similarly, the order in which function arguments are evaluated is not specified, so the statement

can (and does) produce different results on different machines, depending on whether or not n is incremented before power is called. The solution, of course, is to write

Function calls, nested assignment statements, and increment and decrement operators cause "side effects" - some variable is changed as a byproduct of the evaluation of an expression. In any expression involving side effects, there can be subtle dependencies on the order in which variables taking part in the expression are stored. One unhappy situation is typified by the statement

The question is whether the subscript is the old value of i or the new. The compiler can do this in different ways, and generate different answers depending on its interpretation. When side effects (assignment to actual variables) takes place is left to the discretion of the compiler, since the best order strongly depends on machine architecture.

The moral of this discussion is that writing code which depends on order of evaluation is a bad programming practice in any language. Naturally, it is necessary to know what things to avoid, but if you don't know how they are done on various machines, that innocence may help to protect you. (The C verifier lint will detect most dependencies on order of evaluation.)

The real moral of the story is to use side effect operators very carefully. They are generally only used in idiomatic situations and then written using simple code. The authors are happy to tell you everything that you can do in C in great deal and they are also suggesting that just because you can do something that it does not mean you should do something. Remember that a key aspect of writing programs is to communicate with future human readers of your code (including you reading your own code in the future).

With modern-day compilers and optimizers, you gain little performance by writing dense / obtuse code. Write the code and describe what you want done and let the compiler find the best way to do it. One of the reasons that a common senior project in many Computer Science degrees was to write a complier is to make sure all Computer Science students understand that they can trust the compiler to generate great code.

  • 2.1 - Variable Names
  • 2.2 - Data Types and Sizes
  • 2.3 - Constants
  • 2.4 - Declarations
  • 2.5 - Arithmetic Operators
  • 2.6 - Relational and Logical Operators
  • 2.7 - Type Conversions
  • 2.8 - Increment and Decrement Operators
  • 2.9 - Bitwise Logical Operators
  • 2.10 - Assignment Operators and Expressions
  • 2.11 - Conditional Expressions
  • 2.12 - Precedence and Order of Evaluation

Free Computer Science Tutorial

Python for class 11 Tutorial, Python for class 12 Tutorial, C language tutorial, SQL Tutorial, Tips & Tricks, sample papers class 12, C++ tutorial

Assignment Operators in C Language | Shorthand operators in C Language

advantages of shorthand assignment operator in c

Assignment/shorthand operators are used to update the value of a variable in an easy way. There are various assignment operators provided by C language.

  • Programming Language?
  • Introduction
  • Types of Constants in C Language | Types of Literals in C Language
  • Primary data types of C Language | User defined data types in C Language | Derived data types in C Language
  • What is a variable in C Language | Variable naming rules in C Language
  • Display output in C – printf() function
  • Read values in C Language- scanf() function in C Language
  • C – Unformatted Output Function
  • C – Unformatted Input Function
  • 4 Types of Operators in C Language
  • Increment Decrement Operators in C (++ / –)
  • Arithmetic Operators in C Language
  • Relational Operators in C Language | Comparison operators in C Language
  • Logical Operators in C Language | Logical AND in C Language | Logical Or in C Language| Logical NOT in C Language
  • #8508 (no title)
  • Bitwise operators in C | Bitwise Operator programs in C | Bitwise AND in C | Bitwise OR in C | Bitwise XOR in C | Bitwise complement in C | Bitwise left shift in C | Bitwise right shift in C
  • Conditional operator in C Language | Ternary Operator in C Language
  • sizeof() operator in C Language | comma operator in C Language | Special operators in C Language
  • Implicit type Conversion in C Language | Automatic type conversion in C Language
  • Explicit type conversion in C Language | Casting in C Language
  • Precedence and Associativity of Operators in C Language | Expressions in C Language
  • Simple if statement
  • if else statement
  • Nested if statement
  • if else if ladder statement
  • switch statement
  • for statement
  • while statement
  • One dimensional array
  • Two dimensional array
  • Multi dimensional Array
  • Introduction to characters in C Language | Character Variable in C Language | Character Variable Initialization in C Language:
  • Character functions in C Language | isalpha(), isdigit(), isalnum(), ispunct(), isspace(), isupper(), islower(), toupper(), tolower()
  • Strings in c
  •  String functions
  • Array of strings
  • Introduction to function
  • Types of function
  • Call by value | Call by reference
  • Scope of variable in C
  • Storage classes
  • Introduction to pointer
  • Pointer with Array
  • Pointer with Strings
  • Pointer to pointer
  • void type pointer in C Language | using void pointer in C Language
  • Dynamic memory allocation
  • Pointer with function
  • Introduction to Structure
  • Nesting of Structure in C Language | Program of nesting of structure in C Language
  • Declaring Structure type Array in C Language
  • Passing structure type arguments in C Language
  • Function returning structure type data in C Language
  • Structure with Pointers in C Language | Declaring pointer variable of Structure in C Language
  • Self Referential Structure in C Language
  • Introduction to Union in C Language | Declaring Union variable in C Language
  • Introdution to Data File Handling
  • Steps to create a data file
  • File Input output
  • Random Access of Files
  • Command Line Arguments in C Language

You have successfully subscribed.

There was an error while trying to send your request. Please try again.

Subscribe for Latest Updates

cppreference.com

Assignment operators.

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

[ edit ] Simple assignment

The simple assignment operator expressions have the form

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

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

rhs and lhs must satisfy one of the following:

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

[ edit ] Notes

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

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

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

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

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

[ edit ] Compound assignment

The compound assignment operator expressions have the form

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

[ edit ] References

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

[ edit ] See Also

Operator precedence

[ edit ] See also

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

Powered by MediaWiki

Shorthand Operators

Things to do first.

  • Download the notes for this session.
  • Read Chapter 2.13 and 2.14 of your textbook, and do all the CheckPoint, Self-Check, and Exercises in those sections.

Things To Do Later

  • What are the different kinds of assignment operators in Java?
  • What are the unary operators in Java? Why are they referred to as "unary"?
  • How is a post-fix unary operator different from a pre-fix unary operator?
  • Explain the following assignment statement: result = x / y++;
  • How is the assignment statement double result = x / y++; different from the previous one?
  • Assignment Operators
  • Unary Operators

Shorthand Assignment Operators

There are some special assignment operators you can use as shortcuts to certain kinds of assignment statements. To understand how these can be used, look at the program listing below. What is the output of this program? What is the value of the variable "sum" during execution of this program?

This small program demonstrates a situation where you can use the special += assignment operator. This operator, the "plus-equals" operator, adds the operand on the right to the operand on the left. If you rewrote the program using the += operator, you'd have:

There are also similar operators to perform subtraction, division, and modulus. You can see them in Table 2.4 in section 2.13 of your text.

Determine, without coding a program, the output of the following code segment:

[ solutions ]

In addition to the assignment operators, there are also some unary operators. Recall that regular operators, such as +, * and += are binary operators - they require two operands, one on each side. Unary operators require only 1 operand. You can see the unary operators listed in Table 2.5 in Chapter 2.14 of your textbook.

The code listing below demonstrates how the increment operator works:

The output for this program:

Unary operators in Java can go on the left or the right of the operand. The difference is in when the increment actually takes place. Some of the exercises below demonstrate this.

For each of the examples above, type the code into a Java program and print/display the value of "result". Do you get the output you expected? Why or why not?

When the ++ or -- operator is to the left of the operand, we refer to it as a pre-fix operator . When the ++ or -- operator is to the right of the operand, we call it the post-fix operator .

The pre-fix operator has higher precedence than the post-fix operator. In a statement with multiple types of operators, the pre-fix operator will execute before most other operators. The post-fix operator will usually execute after the other operators. See your Operator Precedence chart in Appendix C of your textbook for more information.

When you compile, you'll get the error message

This error message is telling you that the variable x was declared, but was not initialized with a value. Unary operators and the special assignment operators (such as +=) do not work on variables that have not yet been initialized!

1. Examine the code listing below. What do you think the output should be? Write this down. Then run the program and see if you're correct.

IMAGES

  1. Shorthand Assignment Operators

    advantages of shorthand assignment operator in c

  2. Operators in C Programming

    advantages of shorthand assignment operator in c

  3. C Language tutorial||onlinetraining||Shorthand Assignment Operators by Sivaramayya

    advantages of shorthand assignment operator in c

  4. Assignment Operators in C

    advantages of shorthand assignment operator in c

  5. Pointer Expressions in C with Examples

    advantages of shorthand assignment operator in c

  6. Operators In C Logicmojo

    advantages of shorthand assignment operator in c

VIDEO

  1. assignment Operator C Language in Telugu

  2. Assignment Operator in C Programming

  3. Assignment Operator in C Programming

  4. Augmented assignment operators in C

  5. Short hand if else statements in python

  6. Assignment Operator│C programming│Part# 15│Learn CSE Malayalam

COMMENTS

  1. Assignment and shorthand assignment operator in C

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

  2. Assignment Operators in Programming

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

  3. Arithmetical Assignment Operators in C

    Arithmetical assignment operators are shorthand notations that perform arithmetic operations and assignments in a single step. These operators include: For instance, using +=, you can add a value to a variable without needing a separate assignment statement. Similarly, the other operators work by performing the respective operation and updating ...

  4. Assignment Operators in C

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

  5. 4.4: Arithmetic Assignment Operators

    The five arithmetic assignment operators are a form of short hand. Various textbooks call them "compound assignment operators" or "combined assignment operators". Their usage can be explaned in terms of the assignment operator and the arithmetic operators. In the table we will use the variable age and you can assume that it is of integer data type.

  6. C Programming Language: shorthand

    Shorthand in C is extremely simple. Any time you are assigning a value of a variable that uses that variable in the assignment you can simplify the syntax. For example: myVar = myVar + 32; This line of code adds 32 to the current value of 'myVar'. But you don't need to type 'myVar' twice. Instead, move the operator (that's the plus ...

  7. Assignment Expressions (GNU C Language Manual)

    7 Assignment Expressions. As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value. An assignment in C is an expression because it has a value; we call it an assignment expression.

  8. Understanding Shorthand Operator in C Programming Language

    a = a+2; can be written as: a += 2; The operator += tells the compiler that a is assigned the value of a + 2; This shorthand works for all binary operators in C. The general form is variable operator = variable / constant / expression. These operators are listed below: C Shorthand Operators. Operators. Example.

  9. Begin C Programming with C Operators

    C also has some shorthand assignment operators. For Example: x=x+y+1 can be written in shorthand form x+=y+1. The shorthand operator += means "add y+1 to x' or 'increment x by y+1'. If y=2 and x=1, then x after execution would become 5. The advantages of using shorthand are: No repetition of left-hand side and thus the readability is good

  10. Assignment Operators in C

    Assignment operators are used to assigning the result of an expression to a variable. Up to now, we have used the shorthand assignment operator "=", which assigns the result of a right-hand expression to the left-hand variable. For example, in the expression x = y + z, the sum of y and z is assigned to x.

  11. Shorthand Assignment Operators

    In this video, we'll teach you how to use the shorthand assignment operators in C programming language. These operators allow you to write concise and easy t...

  12. What are Shorthand Operators in C++

    Relational Operators. Shorthand Operators are operators that combine one of the arithmetic or bitwise operators with the assignment operator. Shorthand Operators are a shorter way of expressing something that is already available in the programming statements. Expressions or Values can be assigned to the variable using Shorthand Operators.

  13. Shorthand Assignment Operators In C Programming

    Topics Covered in this lecture:1. Shorthand Assignment OperatorsPython Programming Classes by Arvind Kharwalhttps://www.youtube.com/watch?v=uXcHsZtOfik&list=...

  14. Assignment Operators in C

    C Programming & Data Structures: Assignment Operators in CTopics discussed:1. Introduction to Assignment Operators in C language.2. Types of Shorthand Assign...

  15. c++

    x *= a / b; // ^^^^^. This is integer division, the rest is discarded and therefore 3 / 2 is 1. Therefore the expression x *= a / b is the same as x *= 1 which stays 2. x = x * a / b; On the other hand is evaluated as. x = (x * a) / b; The result is then. x = (2 * 3) / 2;

  16. C Assignment Operators

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

  17. 2

    2 - Types, Operators, and Expressions. Variables and constants are the basic data objects manipulated in a program. Declarations list the variables to be used, and state what type they have and perhaps what their initial values are. Operators specify what is to be done to them. Expressions combine variables and constants to produce new values.

  18. Shorthand operators in C Language

    Assignment Operators in C Language | Shorthand operators in C Language. Assignment/shorthand operators are used to update the value of a variable in an easy way. There are various assignment operators provided by C language.

  19. PDF Operators and Expressions

    ASSIGNMENT OPERATORS Assignment operators are used to assign the result of an expression to a variable. We have seen the usual assignment operator, '='. In addition, C has a set of 'shorthand ' assignment operators of the form v op= exp; Where v is a variable, exp is an expression and op is a C binary arithmetic operator. The operator op=

  20. Assignment operators

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

  21. Why are arithmetic assignment operators more efficient?

    An example of thee shorthand Java Arithmetic operator is a += 4; for a=a+4; In The Complete Reference, Java 2, Herbert Schildt mentions "they are implemented more efficiently by the Java run-time system than are their equivalent" What makes its implementation more efficient than a=a+4;

  22. #9: Assignment Operators in C

    This video is a great way to start learning about assignment operators in C. We'll be exploring how these operators work, and how they can be useful for begi...

  23. Shorthand Operators

    This small program demonstrates a situation where you can use the special += assignment operator. This operator, the "plus-equals" operator, adds the operand on the right to the operand on the left. If you rewrote the program using the += operator, you'd have: public class AssignOps {.