assignment result in expression

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Preface
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Variables
  • 1.7 Java Development Environments (optional)
  • 1.8 Unit 1 Summary
  • 1.9 Unit 1 Mixed Up Code Practice
  • 1.10 Unit 1 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.12 Lesson Workspace
  • 1.3. Variables and Data Types" data-toggle="tooltip">
  • 1.5. Compound Assignment Operators' data-toggle="tooltip" >

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

1.4. Expressions and Assignment Statements ¶

In this lesson, you will learn about assignment statements and expressions that contain math operators and variables.

1.4.1. Assignment Statements ¶

Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator = . An assignment statement always has a single variable on the left hand side of the = sign. The value of the expression on the right hand side of the = sign (which can contain math operators and other variables) is copied into the memory location of the variable on the left hand side.

Assignment statement

Figure 1: Assignment Statement (variable = expression) ¶

Instead of saying equals for the = operator in an assignment statement, say “gets” or “is assigned” to remember that the variable on the left hand side gets or is assigned the value on the right. In the figure above, score is assigned the value of 10 times points (which is another variable) plus 5.

The following video by Dr. Colleen Lewis shows how variables can change values in memory using assignment statements.

As we saw in the video, we can set one variable to a copy of the value of another variable like y = x;. This won’t change the value of the variable that you are copying from.

coding exercise

Click on the Show CodeLens button to step through the code and see how the values of the variables change.

The program is supposed to figure out the total money value given the number of dimes, quarters and nickels. There is an error in the calculation of the total. Fix the error to compute the correct amount.

Calculate and print the total pay given the weekly salary and the number of weeks worked. Use string concatenation with the totalPay variable to produce the output Total Pay = $3000 . Don’t hardcode the number 3000 in your print statement.

exercise

Assume you have a package with a given height 3 inches and width 5 inches. If the package is rotated 90 degrees, you should swap the values for the height and width. The code below makes an attempt to swap the values stored in two variables h and w, which represent height and width. Variable h should end up with w’s initial value of 5 and w should get h’s initial value of 3. Unfortunately this code has an error and does not work. Use the CodeLens to step through the code to understand why it fails to swap the values in h and w.

1-4-7: Explain in your own words why the ErrorSwap program code does not swap the values stored in h and w.

Swapping two variables requires a third variable. Before assigning h = w , you need to store the original value of h in the temporary variable. In the mixed up programs below, drag the blocks to the right to put them in the right order.

The following has the correct code that uses a third variable named “temp” to swap the values in h and w.

The code is mixed up and contains one extra block which is not needed in a correct solution. Drag the needed blocks from the left into the correct order on the right, then check your solution. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks.

After three incorrect attempts you will be able to use the Help Me button to make the problem easier.

Fix the code below to perform a correct swap of h and w. You need to add a new variable named temp to use for the swap.

1.4.2. Incrementing the value of a variable ¶

If you use a variable to keep score you would probably increment it (add one to the current value) whenever score should go up. You can do this by setting the variable to the current value of the variable plus one (score = score + 1) as shown below. The formula looks a little crazy in math class, but it makes sense in coding because the variable on the left is set to the value of the arithmetic expression on the right. So, the score variable is set to the previous value of score + 1.

Click on the Show CodeLens button to step through the code and see how the score value changes.

1-4-11: What is the value of b after the following code executes?

  • It sets the value for the variable on the left to the value from evaluating the right side. What is 5 * 2?
  • Correct. 5 * 2 is 10.

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

  • x = 0, y = 1, z = 2
  • These are the initial values in the variable, but the values are changed.
  • x = 1, y = 2, z = 3
  • x changes to y's initial value, y's value is doubled, and z is set to 3
  • x = 2, y = 2, z = 3
  • Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side.
  • x = 1, y = 0, z = 3

1.4.3. Operators ¶

Java uses the standard mathematical operators for addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). Arithmetic expressions can be of type int or double. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value. (You may have noticed that + was also used to put text together in the input program above – more on this when we talk about strings.)

Java uses the operator == to test if the value on the left is equal to the value on the right and != to test if two items are not equal. Don’t get one equal sign = confused with two equal signs == ! They mean different things in Java. One equal sign is used to assign a value to a variable. Two equal signs are used to test a variable to see if it is a certain value and that returns true or false as you’ll see below. Use == and != only with int values and not doubles because double values are an approximation and 3.3333 will not equal 3.3334 even though they are very close.

Run the code below to see all the operators in action. Do all of those operators do what you expected? What about 2 / 3 ? Isn’t surprising that it prints 0 ? See the note below.

When Java sees you doing integer division (or any operation with integers) it assumes you want an integer result so it throws away anything after the decimal point in the answer, essentially rounding down the answer to a whole number. If you need a double answer, you should make at least one of the values in the expression a double like 2.0.

With division, another thing to watch out for is dividing by 0. An attempt to divide an integer by zero will result in an ArithmeticException error message. Try it in one of the active code windows above.

Operators can be used to create compound expressions with more than one operator. You can either use a literal value which is a fixed value like 2, or variables in them. When compound expressions are evaluated, operator precedence rules are used, so that *, /, and % are done before + and -. However, anything in parentheses is done first. It doesn’t hurt to put in extra parentheses if you are unsure as to what will be done first.

In the example below, try to guess what it will print out and then run it to see if you are right. Remember to consider operator precedence .

1-4-15: Consider the following code segment. Be careful about integer division.

What is printed when the code segment is executed?

  • 0.666666666666667
  • Don't forget that division and multiplication will be done first due to operator precedence.
  • Yes, this is equivalent to (5 + ((a/b)*c) - 1).
  • Don't forget that division and multiplication will be done first due to operator precedence, and that an int/int gives an int result where it is rounded down to the nearest int.

1-4-16: Consider the following code segment.

What is the value of the expression?

  • Dividing an integer by an integer results in an integer
  • Correct. Dividing an integer by an integer results in an integer
  • The value 5.5 will be rounded down to 5

1-4-17: Consider the following code segment.

  • Correct. Dividing a double by an integer results in a double
  • Dividing a double by an integer results in a double

1-4-18: Consider the following code segment.

  • Correct. Dividing an integer by an double results in a double
  • Dividing an integer by an double results in a double

1.4.4. The Modulo Operator ¶

The percent sign operator ( % ) is the mod (modulo) or remainder operator. The mod operator ( x % y ) returns the remainder after you divide x (first number) by y (second number) so 5 % 2 will return 1 since 2 goes into 5 two times with a remainder of 1. Remember long division when you had to specify how many times one number went into another evenly and the remainder? That remainder is what is returned by the modulo operator.

../_images/mod-py.png

Figure 2: Long division showing the whole number result and the remainder ¶

In the example below, try to guess what it will print out and then run it to see if you are right.

The result of x % y when x is smaller than y is always x . The value y can’t go into x at all (goes in 0 times), since x is smaller than y , so the result is just x . So if you see 2 % 3 the result is 2 .

1-4-21: What is the result of 158 % 10?

  • This would be the result of 158 divided by 10. modulo gives you the remainder.
  • modulo gives you the remainder after the division.
  • When you divide 158 by 10 you get a remainder of 8.

1-4-22: What is the result of 3 % 8?

  • 8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number!
  • This would be the remainder if the question was 8 % 3 but here we are asking for the reminder after we divide 3 by 8.
  • What is the remainder after you divide 3 by 8?

1.4.5. FlowCharting ¶

Assume you have 16 pieces of pizza and 5 people. If everyone gets the same number of slices, how many slices does each person get? Are there any leftover pieces?

In industry, a flowchart is used to describe a process through symbols and text. A flowchart usually does not show variable declarations, but it can show assignment statements (drawn as rectangle) and output statements (drawn as rhomboid).

The flowchart in figure 3 shows a process to compute the fair distribution of pizza slices among a number of people. The process relies on integer division to determine slices per person, and the mod operator to determine remaining slices.

Flow Chart

Figure 3: Example Flow Chart ¶

A flowchart shows pseudo-code, which is like Java but not exactly the same. Syntactic details like semi-colons are omitted, and input and output is described in abstract terms.

Complete the program based on the process shown in the Figure 3 flowchart. Note the first line of code declares all 4 variables as type int. Add assignment statements and print statements to compute and print the slices per person and leftover slices. Use System.out.println for output.

1.4.6. Storing User Input in Variables ¶

Variables are a powerful abstraction in programming because the same algorithm can be used with different input values saved in variables.

Program input and output

Figure 4: Program input and output ¶

A Java program can ask the user to type in one or more values. The Java class Scanner is used to read from the keyboard input stream, which is referenced by System.in . Normally the keyboard input is typed into a console window, but since this is running in a browser you will type in a small textbox window displayed below the code. The code below shows an example of prompting the user to enter a name and then printing a greeting. The code String name = scan.nextLine() gets the string value you enter as program input and then stores the value in a variable.

Run the program a few times, typing in a different name. The code works for any name: behold, the power of variables!

Run this program to read in a name from the input stream. You can type a different name in the input window shown below the code.

Try stepping through the code with the CodeLens tool to see how the name variable is assigned to the value read by the scanner. You will have to click “Hide CodeLens” and then “Show in CodeLens” to enter a different name for input.

The Scanner class has several useful methods for reading user input. A token is a sequence of characters separated by white space.

Run this program to read in an integer from the input stream. You can type a different integer value in the input window shown below the code.

A rhomboid (slanted rectangle) is used in a flowchart to depict data flowing into and out of a program. The previous flowchart in Figure 3 used a rhomboid to indicate program output. A rhomboid is also used to denote reading a value from the input stream.

Flow Chart

Figure 5: Flow Chart Reading User Input ¶

Figure 5 contains an updated version of the pizza calculator process. The first two steps have been altered to initialize the pizzaSlices and numPeople variables by reading two values from the input stream. In Java this will be done using a Scanner object and reading from System.in.

Complete the program based on the process shown in the Figure 5 flowchart. The program should scan two integer values to initialize pizzaSlices and numPeople. Run the program a few times to experiment with different values for input. What happens if you enter 0 for the number of people? The program will bomb due to division by zero! We will see how to prevent this in a later lesson.

The program below reads two integer values from the input stream and attempts to print the sum. Unfortunately there is a problem with the last line of code that prints the sum.

Run the program and look at the result. When the input is 5 and 7 , the output is Sum is 57 . Both of the + operators in the print statement are performing string concatenation. While the first + operator should perform string concatenation, the second + operator should perform addition. You can force the second + operator to perform addition by putting the arithmetic expression in parentheses ( num1 + num2 ) .

More information on using the Scanner class can be found here https://www.w3schools.com/java/java_user_input.asp

1.4.7. Programming Challenge : Dog Years ¶

In this programming challenge, you will calculate your age, and your pet’s age from your birthdates, and your pet’s age in dog years. In the code below, type in the current year, the year you were born, the year your dog or cat was born (if you don’t have one, make one up!) in the variables below. Then write formulas in assignment statements to calculate how old you are, how old your dog or cat is, and how old they are in dog years which is 7 times a human year. Finally, print it all out.

Calculate your age and your pet’s age from the birthdates, and then your pet’s age in dog years. If you want an extra challenge, try reading the values using a Scanner.

1.4.8. Summary ¶

Arithmetic expressions include expressions of type int and double.

The arithmetic operators consist of +, -, * , /, and % (modulo for the remainder in division).

An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away, essentially rounding down the answer to a whole number.

An arithmetic operation that uses at least one double value will evaluate to a double value.

Operators can be used to construct compound expressions.

During evaluation, operands are associated with operators according to operator precedence to determine how they are grouped. (*, /, % have precedence over + and -, unless parentheses are used to group those.)

An attempt to divide an integer by zero will result in an ArithmeticException to occur.

The assignment operator (=) allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.

During execution, expressions are evaluated to produce a single value.

The value of an expression has a type based on the evaluation of the expression.

This browser is no longer supported.

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

Assignment operators

  • 7 contributors

expression assignment-operator expression

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

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

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

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

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

Assignment operators table

Operator keywords.

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

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

Simple assignment

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

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

Assignment to objects of class type ( struct , union , and class types) is performed by a function named operator= . The default behavior of this operator function is to perform a bitwise copy; however, this behavior can be modified using overloaded operators. For more information, see Operator overloading . Class types can also have copy assignment and move assignment operators. For more information, see Copy constructors and copy assignment operators and Move constructors and move assignment operators .

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

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

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

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

the assignment statement

can have one of the following effects:

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

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

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

Compound assignment

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

an arithmetic type

a pointer, if op is + or -

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

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

Result of assignment operators

The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

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

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

Was this page helpful?

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

Submit and view feedback for

Additional resources

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

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Browser compatibility.

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

  • Assignment operators in the JS guide
  • Destructuring assignment
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Related Articles

  • Solve Coding Problems
  • C++ Variable Templates
  • Unique_ptr in C++
  • vTable And vPtr in C++
  • Difference Between Compile Time And Run Time Polymorphism In C++
  • std::endian in C++ 20
  • Nested Try Blocks in C++
  • String Tokenization in C
  • Variable Shadowing in C++
  • Pass By Reference In C
  • User-Defined Data Types In C
  • Array Decay In C
  • Partial Template Specialization in C++
  • Decision Making in C++
  • Introduction to GUI Programming in C++
  • Literals In C++
  • Attendance Marking System in C++
  • Address Operator & in C
  • C++20 std::basic_syncbuf
  • std::shared_mutex in C++

Assignment Operators In C++

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

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

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

Compound Assignment Operators

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

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

Lets see each of them in detail.

1. Addition Assignment Operator (+=)

In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way.

This above expression is equivalent to the expression:

2. Subtraction Assignment Operator (-=)

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

3. Multiplication Assignment Operator (*=)

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

4. Division Assignment Operator (/=)

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

5. Modulus Assignment Operator (%=)

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

6. Bitwise AND Assignment Operator (&=)

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

7. Bitwise OR Assignment Operator (|=)

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

8. Bitwise XOR Assignment Operator (^=)

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

9. Left Shift Assignment Operator (<<=)

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

10. Right Shift Assignment Operator (>>=)

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

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

Please Login to comment...

  • Geeks Premier League 2023
  • Geeks Premier League

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

cppreference.com

Expressions.

An expression is a sequence of operators and their operands , that specifies a computation.

Expression evaluation may produce a result (e.g., evaluation of 2 + 2 produces the result 4 ) and may generate side-effects (e.g. evaluation of std:: printf ( "%d" , 4 ) prints the character '4' on the standard output).

Each C++ expression is characterized by two independent properties: A type and a value category.

[ edit ] General

  • value categories (lvalue, rvalue , glvalue, prvalue, xvalue (since C++11) ) classify expressions by their values
  • order of evaluation of arguments and subexpressions specify the order in which intermediate results are obtained

[ edit ] Operators

  • operator precedence defines the order in which operators are bound to their arguments
  • alternative representations are alternative spellings for some operators
  • operator overloading makes it possible to specify the behavior of the operators with user-defined classes.

[ edit ] Conversions

  • standard conversions implicit conversions from one type to another
  • const_cast conversion
  • static_cast conversion
  • dynamic_cast conversion
  • reinterpret_cast conversion
  • explicit cast conversion using C-style cast notation and function-style notation
  • user-defined conversion makes it possible to specify conversion from user-defined classes

[ edit ] Memory allocation

  • new expression allocates memory dynamically
  • delete expression deallocates memory dynamically

[ edit ] Other

  • constant expressions can be evaluated at compile time and used in compile-time context (template arguments, array sizes, etc)
  • throw-expression

[ edit ] Primary expressions

The operands of any operator may be other expressions or primary expressions (e.g. in 1 + 2 * 3 , the operands of operator+ are the subexpression 2 * 3 and the primary expression 1 ).

Primary expressions are any of the following:

  • literals (e.g. 2 or "Hello, world" )
  • suitably declared unqualified identifiers (e.g. n or cout ),
  • suitably declared qualified identifiers (e.g. std::string::npos ), and
  • identifiers to be declared in declarators

Any expression in parentheses is also classified as a primary expression: this guarantees that the parentheses have higher precedence than any operator. Parentheses preserve value, type, and value category.

[ edit ] Literals

Literals are the tokens of a C++ program that represent constant values embedded in the source code.

  • integer literals are decimal, octal, hexadecimal or binary numbers of integer type.
  • character literals are individual characters of type
  • char or wchar_t
  • floating-point literals are values of type float , double , or long double
  • string literals are sequences of characters of type
  • const char [ ] or const wchar_t [ ]
  • boolean literals are values of type bool , that is true and false

[ edit ] Full-expressions

A constituent expression is defined as follows:

  • The constituent expression of an expression is that expression.
  • The constituent expressions of a braced-init-list or of a (possibly parenthesized) expression list are the constituent expressions of the elements of the respective list.
  • The constituent expressions of a brace-or-equal-initializer of the form = initializer-clause are the constituent expressions of the initializer-clause .

The immediate subexpressions of an expression E are

  • the constituent expressions of E ’s operands,
  • any function call that E implicitly invokes, or
  • if E is a function call or implicitly invokes a function, the constituent expressions of each default argument used in the call.

A subexpression of an expression E is an immediate subexpression of E or a subexpression of an immediate subexpression of E . Note that expressions appearing in the 'function body' of lambda expressions are not subexpressions of the lambda expression. (since C++11)

A full-expression is

  • an unevaluated operand ,
  • a constant expression ,
  • a declarator of a simple declaration or a member initializer , including the constituent expressions of the initializer,
  • an invocation of a destructor generated at the end of the lifetime of an object other than a temporary object whose lifetime has not been extended, or
  • an expression that is not a subexpression of another expression and that is not otherwise part of a full-expression.

If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition. Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the full-expression.

For an initializer, performing the initialization of the entity (including evaluating default member initializers of an aggregate) (since C++14) is also considered part of the full-expression.

[ edit ] Potentially-evaluated expressions

An expression is potentially evaluated unless

  • it is an unevaluated operand, or
  • it is a subexpression of an unevaluated operand.

[ edit ] Discarded-value expressions

A discarded-value expression is an expression that is used for its side-effects only. The value calculated from such expression is discarded. Such expressions include the full-expression of any expression statement , the left-hand operand of the built-in comma operator, or the operand of a cast-expression that casts to the type void .

Array-to-pointer and function-to-pointer conversions are never applied to the value calculated by a discarded-value expression. The lvalue-to-rvalue conversion is applied if and only if the expression is a volatile-qualified glvalue and has one of the following forms (built-in meaning required, possibly parenthesized):

  • id-expression,
  • array subscript expression,
  • class member access expression,
  • indirection,
  • pointer-to-member operation,
  • conditional expression where both the second and the third operands are one of these expressions,
  • comma expression where the right operand is one of these expressions.

In addition, if the lvalue is of volatile-qualified class type, a volatile copy constructor is required to initialize the resulting rvalue temporary.

[ edit ] Defect reports

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

[ edit ] See also

  • Todo with reason
  • 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 30 December 2023, at 22:45.
  • This page has been accessed 610,427 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 379 – Adding an Assignment Expression

Motivation and summary, specification, examples from the standard library.

This PEP adds a new assignment expression to the Python language to make it possible to assign the result of an expression in almost any place. The new expression will allow the assignment of the result of an expression at first use (in a comparison for example).

Issue1714448 “if something as x:” [1] describes a feature to allow assignment of the result of an expression in an if statement to a name. It supposed that the as syntax could be borrowed for this purpose. Many times it is not the expression itself that is interesting, rather one of the terms that make up the expression. To be clear, something like this:

seems awfully limited, when this:

is probably the desired result.

See the Examples section near the end.

A new expression is proposed with the (nominal) syntax:

This single expression does the following:

  • Evaluate the value of EXPR , an arbitrary expression;
  • Assign the result to VAR , a single assignment target; and
  • Leave the result of EXPR on the Top of Stack (TOS)

Here -> or ( RARROW ) has been used to illustrate the concept that the result of EXPR is assigned to VAR .

The translation of the proposed syntax is:

The assignment target can be either an attribute, a subscript or name:

This expression should be available anywhere that an expression is currently accepted.

All exceptions that are currently raised during invalid assignments will continue to be raised when using the assignment expression. For example, a NameError will be raised when in example 1 and 2 above if name is not previously defined, or an IndexError if index 0 was out of range.

The following two examples were chosen after a brief search through the standard library, specifically both are from ast.py which happened to be open at the time of the search.

Using assignment expression:

The examples shown below highlight some of the desirable features of the assignment expression, and some of the possible corner cases.

  • Assignment in an if statement for use later: def expensive (): import time ; time . sleep ( 1 ) return 'spam' if expensive () -> res in ( 'spam' , 'eggs' ): dosomething ( res )
  • Assignment in a while loop clause: while len ( expensive () -> res ) == 4 : dosomething ( res )
  • Keep the iterator object from the for loop: for ch in expensive () -> res : sell_on_internet ( res )
  • Corner case: for ch -> please_dont in expensive (): pass # who would want to do this? Not I.

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0379.rst

Last modified: 2023-09-09 17:39:29 GMT

  • | New Account
  • | Log In Remember [x]
  • | Forgot Password Login: [x]
  • Format For Printing
  •  -  XML
  •  -  Clone This Bug
  •  -  Top of page

COMMENTS

  1. What is the result of an assignment expression in C?

    1. This is an infinite loop. It first assign 10 to c, then compare it with c > 0, then again loop starts, assign 10 to c, compare it with c>0 and so on. Loop never ends. This is equivalent to the following: while (c=10); /* Because c assign a garbage value, but not true for all cases maybe it assign 0 */ while (c); Edit: It will not return 10 ...

  2. c

    24. The rule is to return the right-hand operand of = converted to the type of the variable which is assigned to. int a; float b; a = b = 4.5; // 4.5 is a double, it gets converted to float and stored into b // this returns a float which is converted to an int and stored in a // the whole expression returns an int. Share.

  3. Assignment operators

    In this article. The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or implicitly convertible to it.

  4. Expressions and operators

    The assignment expression x = f() has now finished evaluating; its result is the new value of x, which is 2. That 2 result in turn is also assigned to y. The assignment expression y = x = f() has now finished evaluating; its result is the new value of y - which happens to be 2. x and y are assigned to 2, and the console has printed "F

  5. Chapter 7

    Assignment as an Expression In C-like languages, an assignment statement itself can be an expression; i.e., the result of the assignment becomes an operand for the expression; e.g.,: while ((ch = getchar())!= EOF){. . .} ch = getchar() is carried out; the result is assigned to ch and becomes the lefthand side of the != operator.

  6. Assignment operators

    The result of a built-in simple assignment is an lvalue of the type of target-expr, referring to target-expr. If target-expr is a bit-field, the result is also a bit-field. Assignment from an expression. If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr.

  7. Assignment Expressions: The Walrus Operator

    In this lesson, you'll learn about the biggest change in Python 3.8: the introduction of assignment expressions.Assignment expression are written with a new notation (:=).This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side.. Assignment expressions allow you to assign and return a value in the same expression.

  8. PEP 572

    PEP 572 - Assignment Expressions Author: Chris Angelico <rosuav at gmail.com>, Tim Peters <tim.peters at gmail.com>, Guido van Rossum <guido at python.org> Status: Final ... Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse ...

  9. 1.4. Expressions and Assignment Statements

    In this lesson, you will learn about assignment statements and expressions that contain math operators and variables. 1.4.1. Assignment Statements ¶. Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator =.

  10. Python's Assignment Operator: Write Robust Assignments

    The third example assigns the result of a math expression to the total variable, while the last example uses a Boolean expression. Note: ... This new statement is known as an assignment expression or named expression. Note: Expressions are a special type of statement in Python. Their distinguishing characteristic is that expressions always have ...

  11. How To Use Assignment Expressions in Python

    An assignment expression binds the value result to the return of slow_calculation with i. You add the result to the newly built list as long as it is greater than 0. In this example, 0, 1, and 2 are all multiplied with themselves, but only the results 1 (1 * 1) and 4 (2 * 2) satisfy the greater than 0 condition and become part of the final list ...

  12. Assignment operators

    The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

  13. The Walrus Operator: Python 3.8 Assignment Expressions

    For Python 3.8, the biggest change is the addition of assignment expressions. Specifically, the := operator gives you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator. This tutorial is an in-depth introduction to the walrus operator.

  14. How can I assign the output of a command to a shell variable?

    A shell assignment is a single word, with no space after the equal sign. So what you wrote assigns an empty value to thefile; furthermore, since the assignment is grouped with a command, it makes thefile an environment variable and the assignment is local to that particular command, i.e. only the call to ls sees the assigned value.. You want to capture the output of a command, so you need to ...

  15. Assignment (=)

    The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables. ... In strict mode, assignment to an unqualified identifier in strict mode will result in a ReferenceError, to avoid the accidental creation of properties on the ...

  16. Assignment Operators in Python

    Syntax. =. Assign value of right side of expression to left side operand. x = y + z. +=. Add and Assign: Add right side operand with left side operand and then assign to left operand. a += b. -=. Subtract AND: Subtract right operand from left operand and then assign to left operand: True if both operands are equal.

  17. Assignment Operators In C++

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

  18. Expressions

    An expression is a sequence of operators and their operands, that specifies a computation.. Expression evaluation may produce a result (e.g., evaluation of 2 + 2 produces the result 4) and may generate side-effects (e.g. evaluation of std:: printf ("%d", 4) prints the character '4' on the standard output).. Each C++ expression is characterized by two independent properties: A type and a value ...

  19. PEP 379

    This single expression does the following: Evaluate the value of EXPR, an arbitrary expression; Assign the result to VAR, a single assignment target; and; Leave the result of EXPR on the Top of Stack (TOS) Here -> or (RARROW) has been used to illustrate the concept that the result of EXPR is assigned to VAR. The translation of the proposed ...

  20. 114076

    Bug 114076 - list-initialization with assignment expression triggers wrong template instanciation. Summary: list-initialization with assignment ... with Clang. GCC rejects b, which is wrong in my opinion. If I understand it correctly, then cases a and b should result in absolutely identical initializations. The destructor of holder should not ...

  21. What does an assignment expression evaluate to in Java?

    5 Answers. The assignment operator in Java evaluates to the assigned value (like it does in, e.g., c ). So here, readLine () will be executed, and its return value stored in line. That stored value is then checked against null, and if it's null then the loop will terminate. the method readLine () is invoked.