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.

  The basics of storing a value.
  Expressions into which a value can be stored.
  Shorthand for changing an lvalue’s contents.
  Shorthand for incrementing and decrementing an lvalue’s contents.
  Accessing then incrementing or decrementing.
  How to avoid ambiguity.
  Write assignments as separate statements.

C Programming Tutorial

  • Call by Value and Call by Reference in C

Last updated on July 27, 2020

C provides two ways of passing arguments to a function.

  • Call by value or Pass by value.
  • Call by reference.

Let's start with Call by value.

Call by Value #

In this method a copy of each of the actual arguments is made first then these values are assigned to the corresponding formal arguments.

reference assignment in c

This means that the changes made by the called function have no effect on the values of actual arguments in the calling function. In the example shown in the above figure, my_func() function modifies a copy of the values of val1 and val2 . However, the original value of val1 and val2 remains the same.

All the function we have written so far uses call by value except the ones in which we passed an array to the function.

Call by reference #

In this method addresses of the actual arguments are copied and then assigned to the corresponding formal arguments. Now formal and actual arguments both points to the same data (because they contain the same address). As a result, any changes made by called function also affect the actual arguments.

Let's take some examples:

The following program demonstrates call by value:

#include<stdio.h> void try_to_change(int, int); int main() { int x = 10, y = 20; printf("Initial value of x = %d\n", x); printf("Initial value of y = %d\n", y); printf("\nCalling the function\n"); try_to_change(x, y); printf("\nValues after function call\n\n"); printf("Final value of x = %d\n", x); printf("Final value of y = %d\n", y); // signal to operating system program ran fine return 0; } void try_to_change(int x, int y) { x = x + 10; y = y + 10; printf("\nValue of x (inside function) = %d\n", x); printf("Value of y (inside function) = %d\n", y); }

Expected Output:

Initial value of x = 10 Initial value of y = 20 Value of x (inside function) = 20 Value of y (inside function) = 30 Values after function call Final value of x = 10 Final value of y = 20

How it works:

The variables x and y inside function main() and variable x and y in the formal arguments of function try_to_change() are completely different. In line 13, when try_to_change() function is called a copy of values of x and y is made and that copy is passed to the formal arguments x and y of the function try_to_change() . Inside the function try_to_change() we have tried to change the original value of x and y by assigning new values to it. Since try_to_change() is working on a copy of x and y , changes made by try_to_change() function will have no effect on the actual arguments x and y .

To use call by reference we need to do two things:

  • Pass the addresses of the actual arguments instead of passing values to the function.
  • Declare the formal arguments of the function as pointer variables of an appropriate type.

The following program demonstrates call by reference.

#include<stdio.h> void try_to_change(int *, int *); int main() { int x = 10, y = 20; printf("Initial value of x = %d\n", x); printf("Initial value of y = %d\n", y); printf("\nCalling the function\n"); try_to_change(&x, &y); printf("\nValues after function call\n\n"); printf("Final value of x = %d\n", x); printf("Final value of y = %d\n", y); // signal to operating system everything works fine return 0; } void try_to_change(int *x, int *y) { (*x)++; (*y)++; printf("\nValue of x (inside function) = %d\n", *x); printf("Value of y (inside function) = %d\n", *y); }
Initial value of x = 10 Initial value of y = 20 Calling the function Value of x (inside function) = 11 Value of y (inside function) = 21 Values after function call Final value of x = 11 Final value of y = 21

Here we are passing addresses of integer variables to a function. So the formal arguments must be declared as a pointer to int or (int *) . The expression (*x)++ means that first dereference the value at x then increment it. Similarly, (*y)++ means that first dereference the value at y then increment it. When the function try_to_change() ends, the control passes back to main() and printf() statements in line 17 and 18 prints the new value of x and y respectively.

Load Comments

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

Recent Posts

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

cppreference.com

Assignment operators.

(C11)
Miscellaneous
General
(C11)
(C99)

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

Operator Operator name Example Description Equivalent of
= basic assignment a = b becomes equal to
+= addition assignment a += b becomes equal to the addition of and a = a + b
-= subtraction assignment a -= b becomes equal to the subtraction of from a = a - b
*= multiplication assignment a *= b becomes equal to the product of and a = a * b
/= division assignment a /= b becomes equal to the division of by a = a / b
%= modulo assignment a %= b becomes equal to the remainder of divided by a = a % b
&= bitwise AND assignment a &= b becomes equal to the bitwise AND of and a = a & b
|= bitwise OR assignment a |= b becomes equal to the bitwise OR of and a = a | b
^= bitwise XOR assignment a ^= b becomes equal to the bitwise XOR of and a = a ^ b
<<= bitwise left shift assignment a <<= b becomes equal to left shifted by a = a << b
>>= bitwise right shift assignment a >>= b becomes equal to right shifted by a = a >> b
Simple assignment Notes Compound assignment References See Also See also

[ edit ] Simple assignment

The simple assignment operator expressions have the form

lhs rhs
lhs - expression of any complete object type
rhs - expression of any type to lhs or with lhs

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)
has type (possibly qualified or atomic(since C11)) _Bool and rhs is a pointer or a value(since C23) (since C99)
has type (possibly qualified or atomic) and rhs has type (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

lhs op rhs
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
lhs, rhs - expressions with (where lhs may be qualified or atomic), except when op is += or -=, which also accept pointer types with the same restrictions as + and -

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

If lhs has type, the operation behaves as a single atomic read-modify-write operation with memory order .

For integer atomic types, the compound assignment @= is equivalent to:

addr = &lhs; T2 val = rhs; T1 old = *addr; T1 new; do { new = old @ val } while (! (addr, &old, new);
(since C11)

[ 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

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b

a[b]
*a
&a
a->b
a.b

a(...)
a, b
(type) a
a ? b : c
sizeof


_Alignof
(since C11)

[ edit ] See also

for Assignment operators
  • 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 09:36.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • Decision Making in C
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • Functions in C
  • C - Functions
  • C - Main Function
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • Arrays in C
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Assignment Operators in C

In C language, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable, or an expression.

The value to be assigned forms the right-hand operand, whereas the variable to be assigned should be the operand to the left of the " = " symbol, which is defined as a simple assignment operator in C.

In addition, C has several augmented assignment operators.

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

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C
+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Simple Assignment Operator (=)

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

You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.

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

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

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

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

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

Augmented Assignment Operators

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

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

Run the code and check its output −

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

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

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

  • Sign In / Suggest an Article

Current ISO C++ status

Upcoming ISO C++ meetings

Upcoming C++ conferences

Compiler conformance status

ISO C++ committee meeting

June 24-29, St. Louis, MO, USA

July 2-5, Folkestone, Kent, UK

value vs ref semantics

Reference and value semantics, what is value and/or reference semantics, and which is best in c++.

With reference semantics, assignment is a pointer-copy (i.e., a reference ). Value (or “copy”) semantics mean assignment copies the value, not just the pointer. C++ gives you the choice: use the assignment operator to copy the value (copy/value semantics), or use a pointer-copy to copy a pointer (reference semantics). C++ allows you to override the assignment operator to do anything your heart desires, however the default (and most common) choice is to copy the value.

Pros of reference semantics: flexibility and dynamic binding (you get dynamic binding in C++ only when you pass by pointer or pass by reference, not when you pass by value).

Pros of value semantics: speed. “Speed” seems like an odd benefit for a feature that requires an object (vs. a pointer) to be copied, but the fact of the matter is that one usually accesses an object more than one copies the object, so the cost of the occasional copies is (usually) more than offset by the benefit of having an actual object rather than a pointer to an object.

There are three cases when you have an actual object as opposed to a pointer to an object: local objects, global/ static objects, and fully contained member objects in a class. The most important of these is the last (“composition”).

More info about copy-vs-reference semantics is given in the next FAQs. Please read them all to get a balanced perspective. The first few have intentionally been slanted toward value semantics, so if you only read the first few of the following FAQs, you’ll get a warped perspective.

Assignment has other issues (e.g., shallow vs. deep copy) which are not covered here.

What is “ virtual data,” and how-can / why-would I use it in C++?

virtual data allows a derived class to change the exact class of a base class’s member object. virtual data isn’t strictly “supported” by C++, however it can be simulated in C++. It ain’t pretty, but it works.

To simulate virtual data in C++, the base class must have a pointer to the member object, and the derived class must provide a new object to be pointed to by the base class’s pointer. The base class would also have one or more normal constructors that provide their own referent (again via new ), and the base class’s destructor would delete the referent.

For example, class Stack might have an Array member object (using a pointer), and derived class StretchableStack might override the base class member data from Array to StretchableArray . For this to work, StretchableArray would have to inherit from Array , so Stack would have an Array* . Stack ’s normal constructors would initialize this Array* with a new Array , but Stack would also have a (possibly protected ) constructor that would accept an Array* from a derived class. StretchableStack ’s constructor would provide a new StretchableArray to this special constructor.

  • Easier implementation of StretchableStack (most of the code is inherited)
  • Users can pass a StretchableStack as a kind-of Stack
  • Adds an extra layer of indirection to access the Array
  • Adds some extra freestore allocation overhead (both new and delete )
  • Adds some extra dynamic binding overhead (reason given in next FAQ)

In other words, we succeeded at making our job easier as the implementer of StretchableStack , but all our users pay for it . Unfortunately the extra overhead was imposed on both users of StretchableStack and on users of Stack .

Please read the rest of this section. ( You will not get a balanced perspective without the others. )

What’s the difference between virtual data and dynamic data?

The easiest way to see the distinction is by an analogy with virtual functions : A virtual member function means the declaration (signature) must stay the same in derived classes, but the definition (body) can be overridden. The overriddenness of an inherited member function is a static property of the derived class; it doesn’t change dynamically throughout the life of any particular object, nor is it possible for distinct objects of the derived class to have distinct definitions of the member function.

Now go back and re-read the previous paragraph, but make these substitutions:

  • “member function” → “member object”
  • “signature” → “type”
  • “body” → “exact class”

After this, you’ll have a working definition of virtual data.

Another way to look at this is to distinguish “per-object” member functions from “dynamic” member functions. A “per-object” member function is a member function that is potentially different in any given instance of an object, and could be implemented by burying a function pointer in the object; this pointer could be const , since the pointer will never be changed throughout the object’s life. A “dynamic” member function is a member function that will change dynamically over time; this could also be implemented by a function pointer, but the function pointer would not be const.

Extending the analogy, this gives us three distinct concepts for data members:

  • virtual data: the definition ( class ) of the member object is overridable in derived classes provided its declaration (“type”) remains the same, and this overriddenness is a static property of the derived class
  • per-object-data: any given object of a class can instantiate a different conformal (same type) member object upon initialization (usually a “wrapper” object), and the exact class of the member object is a static property of the object that wraps it
  • dynamic-data: the member object’s exact class can change dynamically over time

The reason they all look so much the same is that none of this is “supported” in C++. It’s all merely “allowed,” and in this case, the mechanism for faking each of these is the same: a pointer to a (probably abstract) base class. In a language that made these “first class” abstraction mechanisms, the difference would be more striking, since they’d each have a different syntactic variant.

Should I normally use pointers to freestore allocated objects for my data members, or should I use “composition”?

Composition.

Your member objects should normally be “contained” in the composite object (but not always; “wrapper” objects are a good example of where you want a pointer/reference; also the N-to-1-uses-a relationship needs something like a pointer/reference).

There are three reasons why fully contained member objects (“composition”) has better performance than pointers to freestore-allocated member objects:

  • Extra layer of indirection every time you need to access the member object
  • Extra freestore allocations ( new in constructor, delete in destructor)
  • Extra dynamic binding (reason given below)

What are relative costs of the 3 performance hits associated with allocating member objects from the freestore?

The three performance hits are enumerated in the previous FAQ:

  • By itself, an extra layer of indirection is small potatoes
  • Freestore allocations can be a performance issue (the performance of the typical implementation of malloc() degrades when there are many allocations; OO software can easily become “freestore bound” unless you’re careful)
  • The extra dynamic binding comes from having a pointer rather than an object. Whenever the C++ compiler can know an object’s exact class, virtual function calls can be statically bound, which allows inlining. Inlining allows zillions (would you believe half a dozen :-) optimization opportunities such as procedural integration, register lifetime issues, etc. The C++ compiler can know an object’s exact class in three circumstances: local variables, global/ static variables, and fully-contained member objects

Thus fully-contained member objects allow significant optimizations that wouldn’t be possible under the “member objects-by-pointer” approach. This is the main reason that languages which enforce reference-semantics have “inherent” performance challenges.

Note: Please read the next three FAQs to get a balanced perspective!

Are “ inline virtual ” member functions ever actually “inlined”?

Occasionally…

When the object is referenced via a pointer or a reference, a call to a virtual function generally cannot be inlined, since the call must be resolved dynamically. Reason: the compiler can’t know which actual code to call until run-time (i.e., dynamically), since the code may be from a derived class that was created after the caller was compiled.

Therefore the only time an inline virtual call can be inlined is when the compiler knows the “exact class” of the object which is the target of the virtual function call. This can happen only when the compiler has an actual object rather than a pointer or reference to an object. I.e., either with a local object, a global/ static object, or a fully contained object inside a composite. This situation can sometimes happen even with a pointer or reference, for example when functions get inlined, access through a pointer or reference may become direct access on the object.

Note that the difference between inlining and non-inlining is normally much more significant than the difference between a regular function call and a virtual function call. For example, the difference between a regular function call and a virtual function call is often just two extra memory references, but the difference between an inline function and a non- inline function can be as much as an order of magnitude (for zillions of calls to insignificant member functions, loss of inlining virtual functions can result in 25X speed degradation! [Doug Lea, “Customization in C++,” proc Usenix C++ 1990]).

A practical consequence of this insight: don’t get bogged down in the endless debates (or sales tactics!) of compiler/language vendors who compare the cost of a virtual function call on their language/compiler with the same on another language/compiler. Such comparisons are largely meaningless when compared with the ability of the language/compiler to “ inline expand” member function calls. I.e., many language implementation vendors make a big stink about how good their dispatch strategy is, but if these implementations don’t inline member function calls, the overall system performance would be poor, since it is inlining — not dispatching— that has the greatest performance impact.

Here is an example of where virtual calls can be inlined even through a reference. The following code is all in the same translation unit, or otherwise organized such that the optimizer can see all of this code at once.

The compiler is free to transform main as follows:

It is now able to inline the virtual function calls.

Note: Please read the next two FAQs to see the other side of this coin!

Sounds like I should never use reference semantics, right?

Reference semantics are A Good Thing. We can’t live without pointers. We just don’t want our software to be One Gigantic Rats Nest Of Pointers. In C++, you can pick and choose where you want reference semantics (pointers/references) and where you’d like value semantics (where objects physically contain other objects etc). In a large system, there should be a balance. However if you implement absolutely everything as a pointer, you’ll get enormous speed hits.

Objects near the problem skin are larger than higher level objects. The identity of these “problem space” abstractions is usually more important than their “value.” Thus reference semantics should be used for problem-space objects.

Note that these problem space objects are normally at a higher level of abstraction than the solution space objects, so the problem space objects normally have a relatively lower frequency of interaction. Therefore C++ gives us an ideal situation: we choose reference semantics for objects that need unique identity or that are too large to copy, and we can choose value semantics for the others. Thus the highest frequency objects will end up with value semantics, since we install flexibility where it doesn’t hurt us (only), and we install performance where we need it most!

These are some of the many issues that come into play with real OO design. OO/C++ mastery takes time and high quality training. If you want a powerful tool, you’ve got to invest.

Don’t stop now! Read the next FAQ too!!

Does the poor performance of reference semantics mean I should pass-by-value?

The previous FAQ were talking about member objects, not parameters. Generally, objects that are part of an inheritance hierarchy should be passed by reference or by pointer, not by value, since only then do you get the (desired) dynamic binding (pass-by-value doesn’t mix with inheritance, since larger derived class objects get sliced when passed by value as a base class object).

Unless compelling reasons are given to the contrary, member objects should be by value and parameters should be by reference. The discussion in the previous few FAQs indicates some of the “compelling reasons” for when member objects should be by reference.

Please Login to submit a recommendation.

If you don’t have an account, you can register for free.

This browser is no longer supported.

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

Copy constructors and copy assignment operators (C++)

  • 8 contributors

Starting in C++11, two kinds of assignment are supported in the language: copy assignment and move assignment . In this article "assignment" means copy assignment unless explicitly stated otherwise. For information about move assignment, see Move Constructors and Move Assignment Operators (C++) .

Both the assignment operation and the initialization operation cause objects to be copied.

Assignment : When one object's value is assigned to another object, the first object is copied to the second object. So, this code copies the value of b into a :

Initialization : Initialization occurs when you declare a new object, when you pass function arguments by value, or when you return by value from a function.

You can define the semantics of "copy" for objects of class type. For example, consider this code:

The preceding code could mean "copy the contents of FILE1.DAT to FILE2.DAT" or it could mean "ignore FILE2.DAT and make b a second handle to FILE1.DAT." You must attach appropriate copying semantics to each class, as follows:

Use an assignment operator operator= that returns a reference to the class type and takes one parameter that's passed by const reference—for example ClassName& operator=(const ClassName& x); .

Use the copy constructor.

If you don't declare a copy constructor, the compiler generates a member-wise copy constructor for you. Similarly, if you don't declare a copy assignment operator, the compiler generates a member-wise copy assignment operator for you. Declaring a copy constructor doesn't suppress the compiler-generated copy assignment operator, and vice-versa. If you implement either one, we recommend that you implement the other one, too. When you implement both, the meaning of the code is clear.

The copy constructor takes an argument of type ClassName& , where ClassName is the name of the class. For example:

Make the type of the copy constructor's argument const ClassName& whenever possible. This prevents the copy constructor from accidentally changing the copied object. It also lets you copy from const objects.

Compiler generated copy constructors

Compiler-generated copy constructors, like user-defined copy constructors, have a single argument of type "reference to class-name ." An exception is when all base classes and member classes have copy constructors declared as taking a single argument of type const class-name & . In such a case, the compiler-generated copy constructor's argument is also const .

When the argument type to the copy constructor isn't const , initialization by copying a const object generates an error. The reverse isn't true: If the argument is const , you can initialize by copying an object that's not const .

Compiler-generated assignment operators follow the same pattern for const . They take a single argument of type ClassName& unless the assignment operators in all base and member classes take arguments of type const ClassName& . In this case, the generated assignment operator for the class takes a const argument.

When virtual base classes are initialized by copy constructors, whether compiler-generated or user-defined, they're initialized only once: at the point when they are constructed.

The implications are similar to the copy constructor. When the argument type isn't const , assignment from a const object generates an error. The reverse isn't true: If a const value is assigned to a value that's not const , the assignment succeeds.

For more information about overloaded assignment operators, see Assignment .

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

How to Use C++ Reference Variables (C++ Reference Vs Pointer Example)

The concept of references in C++ is simple, interesting and useful to programmers.

It adds value to C++ when compared with C. Though the debate between the followers of C and C++ will always be there but I personally think that both the languages have little overlapping area of usage.

When compared to C, C++ has some very unique features that come in very handy. For example, the concept of references. In this tutorial, we will discuss the reference concept through some practical examples.

What is a Reference?

If I had to summarize the definition of a reference in one line then it would be :

A second name of an existing variable.

It’s like an alias for existing variable. This means that the original variable and the reference both refer to same value and the real beauty of a reference lies in the fact that you can do the same operations on the value through a reference as you could do with the original variable.

If you are new to C++, you should first read about C++ classes and objects .

The Semantics

The following example shows how you can declare a reference in C++

Yes, it’s a very simple syntax with ‘&’ telling the compiler that ‘var’ is a reference variable. But, can you figure out why have explicitly used <some-variable> in the syntax above?

Well, there is a strong reason behind it. Lets take an example to understand this point :

The program shown above is a very simple one. We have not focused on what the program does as we want you to focus on the declaration of reference variable ‘var’.

Now, lets compile this code and see what the compiler has to say :

Oops…the compiler threw an error saying that ‘var’ is not initialized. Yes, that’s what we wanted to convey that references have to initialized at the time of declaration.

So here is the the same program but with correct declaration and some logic involving the reference :

So you see that this time the reference variable ‘var’ was initialized with integer variable ‘a’.

Now lets compile and execute this program :

So, this time the program compiled without any errors. Also, if you try to map the logic with output, you’ll find that an increment operation on reference variable ‘var’ affected the value of  variable ‘a’. This proves that the reference variable and the original variable refer to the same memory location and hence work on the same value.

On a related note, you also might want to understand how to mix C and C++ .

When to Use References?

As with any other programming concept, you should know when to use references to make the most of out of it. I’ll explain here one of the most important scenario in which references should be used.

While working with classes in C++, there are times when you have to pass a class object as an argument to some function. Someone with little or no knowledge of references would pass the object by value. But, do you know that pass by value method is very expensive as all the object data is copied from one variable to the other variable.

With the use of reference, you can define/declare the called function as :

and call the function as :

This way, no copy takes place, just the object ‘obj_recv’ references the same memory (hence the same data) that belongs to the object ‘obj_send’.

So this way you can increase the processing speed of your program significantly by using references.

References and Pointers

While going through last section, some one with good knowledge of pointers could ask that the same thing can be done through pointers also. If this is what struck your mind then you are correct. We can achieve the same through the use of pointers also but references are far more simplified than using pointers.

Though the fact is references are implemented internally in the language through pointers only but the sole purpose of bringing in references in C++ is to leave aside the confusion of pointers.

Here are some of the points that describe why using references is easier :

  • References can be used like normal variables
  • Memory management of references left up to compiler
  • Much cleaner and readable code

You can see the difference between readability and cleanliness of code in the following example that swaps two variables using references and pointers both.

Using References :

Using Pointers :

Things to Take Care

Though references are fairly easy to understand and use, there are some points to take care of :

  • Do not initialize a reference variable with a constant value. This means int &var = 10 is not a valid initialization.
  • Do not return a reference from a function as the memory address that is referred by the reference variable would scope out once the function is done it’s execution.
  • Avoid using references to variables whose memory are dynamically allocated as it might create unnecessary confusion regarding the clean-up of that memory.

If you enjoyed this article, you might also like..

 

Comments on this entry are closed.

You can return a reference from a function; just not a reference to a local variable, because that particular reference will go out of scop and point to garbage.

I’m still learning so all this is great for me. I get to try all this and see what everyone else is talking about. Keep it coming!

Good article.

What would I do it I want to assign a pointer variable to a reference variable? Does it work? Give an example

I have been programming in C/C++ for years but (probably like many others) I like these little tutorials because they give a “quick and dirty” run-through of basic concepts.

Actually, we recommend that a few of class getter methods return ‘const &’. A very basic example using an std::string (we use this mostly for std::map and std::vector)

class A { public: A(const string &s) : m_string(s) {}

const string& getString() { return m_string; } private: std::string m_string; };

This avoids unnecessary copy of data. const string& s1 = a.getString(); // no copy of data! Works great However, if some non-const variable actually wants to modify the data, the compiler would be happy to allow it and copy the data this time: string s2 = a.getString(); s2 += ” something else”.

Another very useful characteristic of using references in method parameters is that they don’t need to be checked for ‘null’, since as explained in the article, they can only be initialized with actual variable references, making them more easy to use than pointers. Also a const string& str means str can not be changed, period. A const char * str puts even intermediate developers in doubt about what exactly is const (pointer or data). However, when you’re dealing with dynamic memory allocations (malloc, new etc), pointers take the cake.

Remeber friends: const references are your friends!

Obviously, the life-time of the object has to be considered. A class whose objects are short-lived, is better off just returning copy of it’s members. But manager objects who stay alive throughout, can manage to return a reference!

Bob, To understand assigning pointers to references, it helps to understand rvalues and lvalues.

In the assignment statement “i = 3;”, 3 is an rvalue, a literal integer 3. i is an lvalue. That is, i is the address of an integer. The thing on the left of an assignment statement has to be an lvalue, and the thing on the right has to be an rvaule. (They get their name from the left and right side of the assignment).

In the statement “i = j;”, j starts out as an lvalue, the address of an int value. The compiler loads the contents of that address to create an rvalue. Then the compiler stores the rvalue into the lvalue address of i.

If pi is of type pointer-to-int, the statement “i = *p;” works as follows. p starts out as an lvalue of type pointer-to-int. The “*” operator dereferences the pointer, that is, it loads the value at the address p. This value is the address of an int, so effectively the compiler has converted an lvalue of type pointer-to-int into an lvalue of type int. The compiler needs an rvalue, so it loads the value at the address it just computed. Then it saves the int rvalue into the address of the lvalue i.

Now lets look at assigning a pointer to a reference. If ri is type int&, then you can write the assignment “ri = *p;” References behave in some ways as if they were pointers. So, p is an lvalue of type pointer-to-int. *p is an rvalue of type pointer-to-int. This rvalue can be assigned directly to ri, which is an lvalue of type pointer-to-int. To answer your question (finally) the way you assign a pointer to a reference is to dereference the pointer with the “*” operator.

This is important lesson, it has very good usage in OOP, as well as functions.

Once I have done some functions for evaluating the value of integral, and numerical methods were used. But it was so hard to read that, just because I have used a lot of * for pointers, the problem was even more difficult just because there were a lot of * for multiplications….

Good to learn this thing!

My question is if i am passing the parameter by reference than,should i return these variable(s) ? or changing any variable in function definition would change it automatically ?

best (Y) clear my mind about function call and related stuff good one

madni; a reference is implemented as a pointer. If you pass a reference to something into a function and then change that thing, it’s changed globally. You don’t have to return it. It’s just like if you passed in a pointer, then de-referenced the pointer to change the pointed-to value.

Anyone know how to create a reference to an object that has an address in absolute memory ? Eg an integer register at address 0x1DF800

This is advanced stuff, only for the stout-hearted. And it’s likely to be undefined behavior. Try this statement.

int& foo = *(int*)0x1DF800;

That is, cast 0x1DF800 to an int* rvalue, then dereference it with the * operator to get an int lvalue, which can initialize the reference. The compiler emits instructions that sets the pointer that internally represents foo to 0x1DF800.

If the value read at that location is a hardware register that can change without action of the program, better cast 0x1DF800 to (volatile int *) or the compiler may cache a previously read value and not re-read the register.

Just to be clear,

volatile int& foo = *(volatile int*)0x1DF800;

well written,really helpful

It is very helpful to know the actual use of references and also difference between references & pointers …

WOW..!! i’ve made my mind even more sharp now regarding these two vital parts of OOP… thanks to you.!! 🙂 ^_^

Next post: How Email Works? – Email Basic Concepts Explained

Previous post: Python Dictionary Examples – Create, Update and Delete Elements

Linux 101 Hacks Book

  • Bash 101 Hacks eBook - Take Control of Your Bash Command Line and Shell Scripting
  • Sed and Awk 101 Hacks eBook - Enhance Your UNIX / Linux Life with Sed and Awk
  • Vim 101 Hacks eBook - Practical Examples for Becoming Fast and Productive in Vim Editor
  • Nagios Core 3 eBook - Monitor Everything, Be Proactive, and Sleep Well

POPULAR POSTS

  • 15 Essential Accessories for Your Nikon or Canon DSLR Camera
  • 12 Amazing and Essential Linux Books To Enrich Your Brain and Library
  • 50 UNIX / Linux Sysadmin Tutorials
  • 50 Most Frequently Used UNIX / Linux Commands (With Examples)
  • How To Be Productive and Get Things Done Using GTD
  • 30 Things To Do When you are Bored and have a Computer
  • Linux Directory Structure (File System Structure) Explained with Examples
  • Linux Crontab: 15 Awesome Cron Job Examples
  • Get a Grip on the Grep! – 15 Practical Grep Command Examples
  • Unix LS Command: 15 Practical Examples
  • 15 Examples To Master Linux Command Line History
  • Top 10 Open Source Bug Tracking System
  • Vi and Vim Macro Tutorial: How To Record and Play
  • Mommy, I found it! -- 15 Practical Linux Find Command Examples
  • 15 Awesome Gmail Tips and Tricks
  • 15 Awesome Google Search Tips and Tricks
  • RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams
  • Can You Top This? 15 Practical Linux Top Command Examples
  • Top 5 Best System Monitoring Tools
  • Top 5 Best Linux OS Distributions
  • How To Monitor Remote Linux Host using Nagios 3.0
  • Awk Introduction Tutorial – 7 Awk Print Examples
  • How to Backup Linux? 15 rsync Command Examples
  • The Ultimate Wget Download Guide With 15 Awesome Examples
  • Top 5 Best Linux Text Editors
  • Packet Analyzer: 15 TCPDUMP Command Examples
  • The Ultimate Bash Array Tutorial with 15 Examples
  • 3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
  • Unix Sed Tutorial: Advanced Sed Substitution Examples
  • UNIX / Linux: 10 Netstat Command Examples
  • The Ultimate Guide for Creating Strong Passwords
  • 6 Steps to Secure Your Home Wireless Network
  • Turbocharge PuTTY with 12 Powerful Add-Ons
  • Linux Tutorials
  • Sed Scripting
  • Awk Scripting
  • Bash Shell Scripting
  • Nagios Monitoring
  • IPTables Firewall
  • Apache Web Server
  • MySQL Database
  • Perl Programming
  • Google Tutorials
  • Ubuntu Tutorials
  • PostgreSQL DB
  • Hello World Examples
  • C Programming
  • C++ Programming
  • DELL Server Tutorials
  • Oracle Database
  • VMware Tutorials

About The Geek Stuff

Copyright © 2008–2024 Ramesh Natarajan. All rights reserved | Terms of Service

  • HORSE RACING
  • MORE SPORTS
  • TSN ARCHIVES
  • Premier League
  • Champions League
  • Europa League
  • Men's March Madness
  • Women's March Madness
  • Men's March Madness Tickets
  • Women's March Madness Tickets
  • Schedule/Results
  • Wrestlemania Tickets
  • United Kingdom

Red Sox reliever taking next step in rehab from Tommy John

Author Photo

The Boston Red Sox have been in desperate need of some help in the bullpen over the last month or so, as the two relievers they added at the deadline (Lucas Sims and Luis Garcia) haven't provided much.

However, according to MassLive's Chris Cotillo , Boston is close to adding another arm to the equation, as Liam Hendriks is expected to start a rehab assignment with Triple-A Worcester on Sunday. He reports that the Red Sox are hoping to see him toss seven total innings with no setbacks.

Hendriks, 35, signed with Boston this offseason on a two-year, $10 million deal knowing that he likely wouldn't pitch most of the year as he recovers from Tommy John surgery he had in 2023.

In his two full seasons with the Chicago White Sox, he posted a 2.66 ERA and an impressive .871 WHIP with a 13.8 K/9. That type of performance would greatly benefit the Red Sox's bullpen at this time. However, even if he's not at that level, he should still be more effective than some of the other relievers Boston has been using recently.

MORE RED SOX NEWS

Red Sox DFA a fan favorite on Friday

Red Sox expected to get star first baseman back

Red Sox pitcher’s MLB debut was ‘dream come true’

Red Sox catcher was upset by DFA at the MLB trade deadline

Mike Masala Photo

Mike Masala previously served as the Managing Editor of USA TODAY's Dolphins Wire as well as a contributing writer at Patriots Wire. Follow on Twitter/X: @Mike_Masala

  • SI SWIMSUIT
  • SI SPORTSBOOK

Pitcher Elects Free Agency Rather Than Staying in Padres' Organization

Valentina martinez | aug 16, 2024.

Jun 11, 2023; Cumberland, Georgia, USA; Washington Nationals relief pitcher Carl Edwards Jr. (58) pitches against the Atlanta Braves during the seventh inning at Truist Park. Mandatory Credit: Dale Zanine-USA TODAY Sports

Pitcher Carl Edwards Jr. cleared waivers and elected free agency. Prior to being designated for assignment on Monday, he had one major league appearance this season with the San Diego Padres.

We have made the following roster moves: pic.twitter.com/u5V2B7aLry — San Diego Padres (@Padres) August 12, 2024

Edwards now has the freedom to sign with any club. The 32-year-old had a brief stint in San Diego after being signed to a minor league deal earlier this summer. It was his second stint in the Padres organization.

In his one appearance on the mound for San Diego, Edwards allowed all three runners he faced to reach base, on two walks and one hit. His teammate, Yuki Matsui, replaced Edwards on the mound and got him out of the jam.

Although he had a nightmarish appearance for the Padres, Edwards' Triple-A numbers were much better.

Edwards split the season between the best affiliates for the Chicago Cubs and the Padres. Edwards posted a 3.30 ERA and has a 22.2 percent strikeout rate. He has a high walk rate with a 14.3 percent clip.

Edwards is able to work out of the bullpen and in the starting rotation. Most recently, he worked out of the Padres' Triple-A rotation.

Edwards spent the 2022-23 season with the Washington Nationals. He had several strong performances out of the bullpen. Through 92.2 innings, he recorded a 3.07 ERA.

In 2023, Edwards was hampered by a stress fracture in his right shoulder that ended his season. Due to his injury, he was limited to a minor league deal in the offseason.

The Cubs signed Edwards to a minor league contract, but after he didn't make the big league roster, he opted out in June. In July, he signed a minor league deal with the Padres.

Given his latest move, it's evident that Edwards is hoping to find a roster spot with any big league team that'll take him. The Padres have one of the strongest bullpens in MLB so it was unlikely that he would make their final roster.

The Padres have won 19 of their last 22 games for the first time in the franchise's history. San Diego is hitting .289, a league best, and scoring an average of 6.1 runs, also a league best. The club has also allowed the fewest runs per game of any major league team (3.1) in this stretch.

“It’s something we’ve built over the course of the season,” Jake Cronenworth told Kevin Acee of the San Diego Union-Tribune . “… The level of intent and work and what we’re trying to do every time we come to the park every day — and that’s win, but with that goal in mind — it’s just that same drive of focus every day on that specific game.”

Valentina Martinez

VALENTINA MARTINEZ

  • Skip to content
  • Skip to search
  • Skip to footer

Security Configuration Guide, Cisco IOS XE 17.15.x (Catalyst 9600 Switches)

Bias-free language.

The documentation set for this product strives to use bias-free language. For the purposes of this documentation set, bias-free is defined as language that does not imply discrimination based on age, disability, gender, racial identity, ethnic identity, sexual orientation, socioeconomic status, and intersectionality. Exceptions may be present in the documentation due to language that is hardcoded in the user interfaces of the product software, language used based on RFP documentation, or language that is used by a referenced third-party product. Learn more about how Cisco is using Inclusive Language.

  • Controlling Switch Access with Passwords and Privilege Levels
  • Configuring Login Block
  • Configuring Authentication

Configuring Authorization

  • Configuring Accounting
  • Configuring Local Authentication and Authorization
  • Configuring AAA Authorization and Authentication Cache
  • Configuring AAA Dead-Server Detection
  • Configuring TACACS+
  • Configuring RADIUS
  • Configuring RadSec
  • Configuring RADIUS Server Load Balancing
  • Configuring VLAN RADIUS Attributes
  • Device Sensor
  • Configuring Kerberos
  • Configuring MACsec Encryption
  • Configuring Secure Shell
  • Secure Shell Version 2 Support
  • SSH Support Over IPv6
  • Configuring SSH File Transfer Protocol
  • X.509v3 Certificates for SSH Authentication
  • SSH Algorithms for Common Criteria Certification
  • Configuring Secure Socket Layer HTTP
  • Object Groups for ACLs
  • Configuring Reflexive Access Lists
  • Configuring IP Source Guard
  • Configuring Dynamic ARP Inspection
  • Configuring IPv6 First Hop Security
  • Configuring Switch Integrated Security Features
  • Configuring IEEE 802.1x Port-Based Authentication

IEEE 802.1X VLAN Assignment

  • Web-Based Authentication
  • Identity Based Networking Services Overview
  • Change of Authorization Support
  • Configuring Identity Control Policies
  • Policy Classification Engine
  • Configuring Identity Service Templates
  • Interface Templates
  • eEdge Integration with MACsec
  • Critical Voice VLAN Support
  • Configuring Local Authentication Using LDAP
  • Web Authentication Redirection to Original URL
  • Port-Based Traffic Control
  • Port Security
  • Configuring Control Plane Policing
  • Configuring Lawful Intercept
  • Configuring Authorization and Revocation of Certificates in a PKI
  • Source Interface Selection for Outgoing Traffic with Certificate Authority
  • Source Interface and VRF Support in LDAP
  • Configuring IPv6 Support for LDAP
  • Secure Operation in FIPS Mode
  • Troubleshooting Security

Clear Contents of Search

Chapter: IEEE 802.1X VLAN Assignment

Prerequisites for ieee 802.1x vlan assignment, restrictions for ieee 802.1x vlan assignment, ieee 802.1x authentication with vlan assignment, enabling aaa authorization for vlan assignment, enabling ieee 802.1x authentication and authorization, specifying an authorized vlan in the radius server database, example: enabling aaa authorization for vlan assignment, example: enabling 802.1x authentication, additional references for ieee 802.1x port-based authentication, feature history for ieee 802.1x vlan assignment.

The IEEE 802.1X VLAN Assignment feature is automatically enabled when IEEE 802.1X authentication is configured for an access port, which allows the RADIUS server to send a VLAN assignment to the device port. This assignment configures the device port so that network access can be limited for certain users.

The following tasks must be completed before implementing the IEEE 802.1X VLAN Assignment feature:

IEEE 802.1X must be enabled on the device port.

The device must have a RADIUS configuration and be connected to the Cisco secure access control server (ACS). You should understand the concepts of the RADIUS protocol and have an understanding of how to create and apply access control lists (ACLs).

EAP support must be enabled on the RADIUS server.

You must configure the IEEE 802.1X supplicant to send an EAP-logoff (Stop) message to the switch when the user logs off. If you do not configure the IEEE 802.1X supplicant, an EAP-logoff message is not sent to the switch and the accompanying accounting Stop message is not sent to the authentication server. See the Microsoft Knowledge Base article at the location http://support.microsoft.com and set the SupplicantMode registry to 3 and the AuthMode registry to 1.

Authentication, authorization, and accounting (AAA) must be configured on the port for all network-related service requests. The authentication method list must be enabled and specified. A method list describes the sequence and authentication method to be queried to authenticate a user. See the IEEE 802.1X Authenticator feature module for information.

The port must be successfully authenticated.

The IEEE 802.1X VLAN Assignment feature is available only on Cisco 89x and 88x series integrated switching routers (ISRs) that support switch ports.

The following ISR-G2 routers are supported:

The following cards or modules support switch ports:

Enhanced High-speed WAN interface cards (EHWICs) with ACL support:

EHWIC-4ESG-P

EHWIC-9ESG-P

High-speed WAN interface cards (HWICs) without ACL support:

HWIC-4ESW-P

HWIC-9ESW-P

The IEEE 802.1X VLAN Assignment feature is available only on a switch port.

The device port is always assigned to the configured access VLAN when any of the following conditions occurs:

No VLAN is supplied by the RADIUS server.

The VLAN information from the RADIUS server is not valid.

IEEE 802.1X authentication is disabled on the port.

The port is in the force authorized, force unauthorized, unauthorized, or shutdown state.

Assignment to the configured access VLAN prevents ports from appearing unexpectedly in an inappropriate VLAN because of a configuration error. Examples of configuration errors include the following:

A nonexistent or malformed VLAN ID

Attempted assignment to a voice VLAN ID

When IEEE 802.1X authentication is enabled on a port, you cannot configure a port VLAN that is equal to a voice VLAN.

If the multihost mode is enabled on an IEEE 802.1X port, all hosts are placed in the same VLAN (specified by the RADIUS server) as the first authenticated host.

If an IEEE 802.1X port is authenticated and put in the RADIUS server-assigned VLAN, any change to the port access VLAN configuration does not take effect.

This feature does not support standard ACLs on the switch port.

Information About IEEE 802.1X VLAN Assignment

The AAA authorization feature is used to determine what a user can and cannot do. When AAA authorization is enabled, the network access server uses information retrieved from the user profile that is located either in the local user database or on the security server, to configure the user’s session. The user is granted access to a requested service only if the information in the user profile allows it.

Device ports support IEEE 802.1X authentication with VLAN assignment. After successful IEEE 802.1X authentication of a port, the RADIUS server sends the VLAN assignment to configure the device port.

The RADIUS server database maintains the username-to-VLAN mappings, assigning the VLAN based on the username of the supplicant connected to the device port.

How to Configure IEEE 802.1X VLAN Assignment

AAA authorization limits the services available to a user. When AAA authorization is enabled, the device uses information retrieved from the user's profile, which is in the local user database or on the security server, to configure the user's session. The user is granted access to a requested service only if the information in the user profile allows it.

  Command or Action Purpose

enable

configure terminal

aaa new-model

aaa authorization network radius if-authenticated

aaa authorization exec radius if-authenticated

end

  Command or Action Purpose

enable

configure terminal

aaa new-model

aaa authentication dot1x {default | } [ ]

dot1x system-auth-control

identity profile default

exit

interface /

access-session port-control {auto | force-authorized | force-unauthorized}

—Enables IEEE 802.1X authentication and causes the port to begin in the unauthorized state, allowing only EAPOL frames to be sent and received through the port. The authentication process begins when the link state of the port changes from down to up or when an EAPOL-start frame is received. The Device requests the identity of the supplicant and begins relaying authentication messages between the supplicant and the authentication server. Each supplicant attempting to access the network is uniquely identified by the Device by using the supplicant MAC address.

-—Disables IEEE 802.1X authentication and causes the port to change to the authorized state without any authentication exchange required. The port sends and receives normal traffic without IEEE 802.1X-based authentication of the client. This is the default setting.

—Causes the port to remain in the unauthorized state, ignoring all attempts by the supplicant to authenticate. The Device cannot provide authentication services to the supplicant through the port.

dot1x pae [supplicant | authenticator | both]

—The interface acts only as a supplicant and does not respond to messages that are meant for an authenticator.

-—The interface acts only as an authenticator and does not respond to any messages meant for a supplicant.

—The interface behaves both as a supplicant and as an authenticator and thus does respond to all dot1x messages.

end

show dot1x

The Internet Engineering Task Force (IETF) draft standard specifies a method for communicating vendor-specific information between the device and the RADIUS server by using the vendor-specific attribute (attribute 26). Vendor-specific attributes (VSAs) allow vendors to support their own extended attributes not suitable for general use. The Cisco RADIUS implementation supports one vendor-specific option by using the format recommended in the specification.

You must assign the following vendor-specific tunnel attributes in the RADIUS server database. The RADIUS server must return these attributes to the device:

[64] Tunnel-Type = VLAN

[65] Tunnel-Medium-Type = 802

[81] Tunnel-Private-Group-ID = VLAN name or VLAN ID

Attribute [64] must contain the value “VLAN” (type 13). Attribute [65] must contain the value “802” (type 6). Attribute [81] specifies the VLAN name or VLAN ID assigned to the IEEE 802.1X-authenticated user.

Configuration Examples for IEEE 802.1X VLAN Assignment

The following example shows how to enable AAA Authorization for VLAN assignment:

The following example shows how to enable 802.1X authentication on a device:

The following show dot1x command output shows that 802.1X authentication has been configured on a device:

Standards and RFCs

Standard/RFC Title

IEEE 802.1X

RFC 3580

Technical Assistance

Description

Link

The Cisco Support website provides extensive online resources, including documentation and tools for troubleshooting and resolving technical issues with Cisco products and technologies.

To receive security and technical information about your products, you can subscribe to various services, such as the Product Alert Tool (accessed from Field Notices), the Cisco Technical Services Newsletter, and Really Simple Syndication (RSS) Feeds.

Access to most tools on the Cisco Support website requires a Cisco.com user ID and password.

This table provides release and related information for the features explained in this module.

These features are available in all the releases subsequent to the one they were introduced in, unless noted otherwise.

Release

Feature

Feature Information

Cisco IOS XE Gibraltar 16.11.1

IEEE 802.1X VLAN Assignment

The IEEE 802.1X VLAN Assignment feature is automatically enabled when IEEE 802.1X authentication is configured for an access port, which allows the RADIUS server to send a VLAN assignment to the device port. This assignment configures the device port so that network access can be limited for certain users.

Use the Cisco Feature Navigator to find information about platform and software image support. To access Cisco Feature Navigator, go to http://www.cisco.com/go/cfn .

Was this Document Helpful?

Feedback

Contact Cisco

login required

  • (Requires a Cisco Service Contract )

reference assignment in c

reference assignment in c

KB5042320: Windows Recovery Environment update for Windows 10, version 21H2 and 22H2: January 9, 2024

IMPORTANT  This update will not be offered if your Windows Recovery Environment (WinRE) meets any of the following conditions:

If the WinRE recovery partition does not have sufficient free space, see the NOTE in the "Summary" section. The note provides instructions about how to increase the available free space in the WinRE recovery partition.

If the WinRE recovery partition was manually updated by using the procedure in Add an update package to Windows RE  and is already up to date.

If the WinRE image has a version greater than or equal to version 10.0.19041.3920 . To determine the version of your WinRE image, check the WinREVersion registry value at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion .

If your running PC does not have a WinRE recovery partition. To verify if you have WinRE enabled, run the following command in an elevated command prompt:  reagentc /info . If WinRE is enabled, you will see  Windows RE status  in the output with a value of  Enabled . In this scenario, this update might be needed.

in the “Summary” section about how to increase the available free space in the WinRE recovery partition.

note at the top of the article. This note combines the conditions under which this WinRE update is not needed and will not be offered.

 in the "Summary" section about how to increase the WinRE recovery partition to 250 MB of free space.

This update automatically applies Safe OS Dynamic Update ( KB5034232 ) to the Windows Recovery Environment (WinRE) on a running PC. The update installs improvements to Windows recovery features.

This update requires 250 MB of free space in the recovery partition to install successfully.

If you would like to make sure your device is offered this update, please follow the   or use a   to increase the size of the WinRE recovery partition.

Once your partition has sufficient disk space, click   >   >   >   to have the update offered to you and then install it.

How to get this update

This update is available through the following release channels.

Windows Update

Yes

Microsoft Update Catalog

No

Windows Server Update Services (WSUS) and Microsoft Endpoint Configuration Manager

No

The PC must have 250 MB of free space in the recovery partition to apply this update successfully.

You do not need to restart your device after applying this update.

After installing this update, the WinRE version installed on the device should greater than or equal to version ​​​​​​​. 

To determine the version of your WinRE image, check the registry value at .

This update cannot be removed once it is applied to a Windows image.

This update replaces the previously released update KB5034441.

Description of the standard terminology that is used to describe Microsoft software updates

Facebook

Need more help?

Want more options.

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

reference assignment in c

Microsoft 365 subscription benefits

reference assignment in c

Microsoft 365 training

reference assignment in c

Microsoft security

reference assignment in c

Accessibility center

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

reference assignment in c

Ask the Microsoft Community

reference assignment in c

Microsoft Tech Community

reference assignment in c

Windows Insiders

Microsoft 365 Insiders

Was this information helpful?

Thank you for your feedback.

You are viewing this page in an unauthorized frame window.

This is a potential security issue, you are being redirected to https://nvd.nist.gov

You have JavaScript disabled. This site requires JavaScript to be enabled for complete site functionality.

Official websites use .gov A .gov website belongs to an official government organization in the United States.

Information Technology Laboratory

National vulnerability database.

  • Vulnerabilities

The NVD has a new announcement page with status updates, news, and how to stay connected!

CVE-2024-7646 Detail

A security issue was discovered in ingress-nginx where an actor with permission to create Ingress objects (in the `networking.k8s.io` or `extensions` API group) can bypass annotation validation to inject arbitrary commands and obtain the credentials of the ingress-nginx controller. In the default configuration, that credential has access to all secrets in the cluster.


   NVD  NVD     Kubernetes     CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H -->

 NVD   -->

By selecting these links, you will be leaving NIST webspace. We have provided these links to other web sites because they may have information that would be of interest to you. No inferences should be drawn on account of other sites being referenced, or not, from this page. There may be other web sites that are more appropriate for your purpose. NIST does not necessarily endorse the views expressed, or concur with the facts presented on these sites. Further, NIST does not endorse any commercial products that may be mentioned on these sites. Please address comments about this page to .

Hyperlink Resource

Weakness Enumeration

CWE-ID CWE Name Source
Improper Input Validation Kubernetes  

Change History

New cve received by nist 8/16/2024 2:15:10 pm.

Action Type Old Value New Value
Added CVSS V3.1

Added CWE

Added Description

Added Reference

Added Reference

Added Reference

Added Reference

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Why must the copy assignment operator return a reference/const reference? [duplicate]

In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the new object? In addition, if I have class A , and the following:

The operator= is defined as follows:

  • operator-overloading
  • copy-constructor
  • assignment-operator

Azeem's user avatar

  • 4 There's no such requirement. But if you want to stick to the principle of least surprize you'll return A& just like a=b is an lvalue expression referring to a in case a and b are ints. –  sellibitze Commented Jun 24, 2010 at 6:23
  • @MattMcNabb Thank you for letting me know! Will do that –  bks Commented Feb 20, 2015 at 6:35
  • Why cant we return A* from the copy assignment operator I guess the chaining assignment would still work properly. Can anyone help understand the perils of returning A* if there are any. –  krishna Commented Mar 19, 2015 at 7:35
  • 1 Note: Since C++11 there is also the move-assignment operator , all the same logic in this Q & A also applies to the move-assignment operator. In fact they could both be the same function if declared as A & operator=(A a); , i.e. taking the argument by value. –  M.M Commented Mar 27, 2015 at 2:28
  • 1 There is now also a C++ Core Guideline regarding this, explaining the historical context as well. –  MakisH Commented Feb 22, 2022 at 20:38

8 Answers 8

A bit of clarification as to why it's preferable to return by reference for operator= versus return by value --- as the chain a = b = c will work fine if a value is returned.

If you return a reference, minimal work is done. The values from one object are copied to another object.

However, if you return by value for operator= , you will call a constructor AND destructor EACH time that the assignment operator is called!!

In sum, there is nothing gained by returning by value, but a lot to lose.

( Note : This isn't meant to address the advantages of having the assignment operator return an lvalue. Read the other posts for why that might be preferable)

Alex Collins's user avatar

  • What I find annoying is that you're allowed to return a stupid type. I think it should enforce the non-const ref of the type... Although to delete the function, whatever it returns doesn't matter much. –  Alexis Wilke Commented Feb 4, 2021 at 23:50

Strictly speaking, the result of a copy assignment operator doesn't need to return a reference, though to mimic the default behavior the C++ compiler uses, it should return a non-const reference to the object that is assigned to (an implicitly generated copy assignment operator will return a non-const reference - C++03: 12.8/10). I've seen a fair bit of code that returns void from copy assignment overloads, and I can't recall when that caused a serious problem. Returning void will prevent users from 'assignment chaining' ( a = b = c; ), and will prevent using the result of an assignment in a test expression, for example. While that kind of code is by no means unheard of, I also don't think it's particularly common - especially for non-primitive types (unless the interface for a class intends for these kinds of tests, such as for iostreams).

I'm not recommending that you do this, just pointing out that it's permitted and that it doesn't seem to cause a whole lot of problems.

These other SO questions are related (probably not quite dupes) that have information/opinions that might be of interest to you.

  • Has anyone found the need to declare the return parameter of a copy assignment operator const?
  • Overloading assignment operator in C++

Community's user avatar

  • I found it useful to return void on the assignment operator when I needed to prevent the automatic destruction of objects as they came of the stack. For ref-counted objects, you don't want destructors being called when you don't know about them. –  cjcurrie Commented Jan 12, 2013 at 13:54

When you overload operator= , you can write it to return whatever type you want. If you want to badly enough, you can overload X::operator= to return (for example) an instance of some completely different class Y or Z . This is generally highly inadvisable though.

In particular, you usually want to support chaining of operator= just like C does. For example:

That being the case, you usually want to return an lvalue or rvalue of the type being assigned to. That only leaves the question of whether to return a reference to X, a const reference to X, or an X (by value).

Returning a const reference to X is generally a poor idea. In particular, a const reference is allowed to bind to a temporary object. The lifetime of the temporary is extended to the lifetime of the reference to which it's bound--but not recursively to the lifetime of whatever that might be assigned to. This makes it easy to return a dangling reference--the const reference binds to a temporary object. That object's lifetime is extended to the lifetime of the reference (which ends at the end of the function). By the time the function returns, the lifetime of the reference and temporary have ended, so what's assigned is a dangling reference.

Of course, returning a non-const reference doesn't provide complete protection against this, but at least makes you work a little harder at it. You can still (for example) define some local, and return a reference to it (but most compilers can and will warn about this too).

Returning a value instead of a reference has both theoretical and practical problems. On the theoretical side, you have a basic disconnect between = normally means and what it means in this case. In particular, where assignment normally means "take this existing source and assign its value to this existing destination", it starts to mean something more like "take this existing source, create a copy of it, and assign that value to this existing destination."

From a practical viewpoint, especially before rvalue references were invented, that could have a significant impact on performance--creating an entire new object in the course of copying A to B was unexpected and often quite slow. If, for example, I had a small vector, and assigned it to a larger vector, I'd expect that to take, at most, time to copy elements of the small vector plus a (little) fixed overhead to adjust the size of the destination vector. If that instead involved two copies, one from source to temp, another from temp to destination, and (worse) a dynamic allocation for the temporary vector, my expectation about the complexity of the operation would be entirely destroyed. For a small vector, the time for the dynamic allocation could easily be many times higher than the time to copy the elements.

The only other option (added in C++11) would be to return an rvalue reference. This could easily lead to unexpected results--a chained assignment like a=b=c; could destroy the contents of b and/or c , which would be quite unexpected.

That leaves returning a normal reference (not a reference to const, nor an rvalue reference) as the only option that (reasonably) dependably produces what most people normally want.

Jerry Coffin's user avatar

  • I don't see which danger situation you are referring to in the "Returning a const reference" part; if someone writes const T &ref = T{} = t; then it is a dangling reference regardless of whether operator= returned T& or T const & . Ironically it is fine if the operator= returned by value! –  M.M Commented Feb 19, 2015 at 3:44
  • @MattMcNabb: Oops--that was supposed to say lvalue reference . Thanks for pointing it out (because yes, an rvalue reference is clearly a bad idea here). –  Jerry Coffin Commented Mar 27, 2015 at 2:45

It's partly because returning a reference to self is faster than returning by value, but in addition, it's to allow the original semantics that exist in primitive types.

Puppy's user avatar

  • Not going to vote down, but I'd like to point out that returning by value would make no sense. Imagine (a = b = c) if (a = b) returned 'a' by value. Your latter point is very legit. –  stinky472 Commented Jun 25, 2010 at 12:45
  • 5 You'd get (a = (b = c)), I believe, which would still produce the intended result. Only if you did (a = b) = c would it be broken. –  Puppy Commented Jun 25, 2010 at 12:51

operator= can be defined to return whatever you want. You need to be more specific as to what the problem actually is; I suspect that you have the copy constructor use operator= internally and that causes a stack overflow, as the copy constructor calls operator= which must use the copy constructor to return A by value ad infinitum.

MSN's user avatar

  • That would be a lame (and unusual) copy-ctor implementation. The reason to return A& from A::operator= is different in most cases. –  jpalecek Commented Jun 25, 2010 at 11:53
  • @jpalecek, I agree, but given the original post and lack of clarity when stating the actual problem, it is most likely that the assignment operator executing results in a stackoverflow due to infinite recursion. If there is another explanation for this question I would love to know it. –  MSN Commented Jun 28, 2010 at 21:18
  • @MSN I dont know it was his problem or not . But surely your post here has addressed my problem +1 for that –  Invictus Commented Apr 1, 2012 at 18:39

There is no core language requirement on the result type of a user-defined operator= , but the standard library does have such a requirement:

C++98 §23.1/3:

” The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

C++98 §23.1/4:

” In Table 64, T is the type used to instantiate the container, t is a value of T , and u is a value of (possibly const ) T .

Returning a copy by value would still support assignment chaining like a = b = c = 42; , because the assignment operator is right-associative, i.e. this is parsed as a = (b = (c = 42)); . But returning a copy would prohibit meaningless constructions like (a = b) = 666; . For a small class returning a copy could conceivably be most efficient, while for a larger class returning by reference will generally be most efficient (and a copy, prohibitively inefficient).

Until I learned about the standard library requirement I used to let operator= return void , for efficiency and to avoid the absurdity of supporting side-effect based bad code.

With C++11 there is additionally the requirement of T& result type for default -ing the assignment operator, because

C++11 §8.4.2/1:

” A function that is explicitly defaulted shall […] have the same declared function type (except for possibly differing ref-qualifiers and except that in the case of a copy constructor or copy assignment operator, the parameter type may be “reference to non-const T ”, where T is the name of the member function’s class) as if it had been implicitly declared

Cheers and hth. - Alf's user avatar

  • Copy assignment should not be void , otherwise assignment chain will not work
  • Copy assignment should not return a value, otherwise unnecessary copy constructor and destructor will be called
  • Copy assignment should not return rvalue reference cos it may have the assigned object moved . Again take the assignment chain for example

Silentroar's user avatar

I guess, because user defined object should behave like builtin types. For example:

baz's user avatar

Not the answer you're looking for? Browse other questions tagged c++ operator-overloading copy-constructor assignment-operator or ask your own question .

  • The Overflow Blog
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Is there a "simplest" way to embed a graph in 3-space?
  • What majority age is taken into consideration when travelling from country to country?
  • DIN Rail Logic Gate
  • What is the meaning of these two words? (Greek)
  • MOSFETs keep shorting way below rated current
  • Is it good idea to divide a paper in pure mathematics?
  • Colorless Higgs
  • Simple JSON parser in lisp
  • Cover letter format in Germany
  • Will the US Customs be suspicious of my luggage if i bought a lot of the same item?
  • Why do these finite group Dedekind matrices seem to have integer spectrum when specialized to the order of group elements?
  • Power line crossing data lines via the ground plane
  • Enigmatic Puzzle 4: Three Leaf Clover
  • How predictable are the voting records of members of the US legislative branch?
  • Did the United States have consent from Texas to cede a piece of land that was part of Texas?
  • Why was I was allowed to bring 1.5 liters of liquid through security at Frankfurt Airport?
  • Sci-fi book about humanity warring against aliens that eliminate all species in the galaxy
  • What is the connection between a regular language's pumping number, and the number of states of an equivalent deterministic automaton?
  • Has anybody replaced a LM723 for a ua723 and experienced problems with drift and oscillations
  • Trace operation as contraction - how can we contract only contravariant indices?
  • Can I use the Chi-square statistic to evaluate theoretical PDFs against an empirical dataset of 60,000 values?
  • What makes a new chain suck other than a worn cassette?
  • Has technology regressed in the Alien universe?
  • Stargate "instructional" videos

reference assignment in c

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Why Assignment Operator Overloading Must Return Reference?

Operator overloading in C++ allows us to define custom behaviors for operators when applied to user-defined types. One of the most commonly overloaded operators is the assignment operator (=), which is used to assign the value of one object to another. However, when overloading the assignment operator, it’s important to ensure that it returns a reference to the object being assigned. But why is this necessary?

In this article, we will learn why the assignment operator must return a reference in C++ when overloading, and what could go wrong if it doesn’t.

Why Must the Assignment Operator Return a Reference?

When overloading the assignment operator in C++ , it’s important that it returns a reference to the object being assigned. There are several key reasons for this:

1. Chaining of Assignment Operations

In C++, assignment operations can be chained together.

For example:

To support this chaining, the assignment operator must return a reference to the object being assigned. This allows the operation b = c to return b, enabling a = b to work as expected.

2. Consistency with Built-in Types

For built-in types, the assignment operator in C++ returns a reference to the left-hand operand. To maintain consistency and intuitive behavior for user-defined types, overloaded assignment operators should also return a reference.

3. Avoiding Unnecessary Object Copies

If the assignment operator returned an object by value instead of by reference, it would result in the creation of a temporary object, which is immediately discarded. This unnecessary copying is inefficient and could lead to performance issues, especially for large objects or objects managing dynamic resources.

C++ Program to Demonstrate Properly Overloading the Assignment Operator

The below example demonstartes how to properly overload the assignment operator in C++.

What Happens if Assignment Operator Does Not Return a Reference?

If we overload the assignment operator and return by value instead of by reference, several issues could arise:

  • Chained assignments like a = b = c; would not work correctly.
  • Returning by value would create temporary objects, leading to inefficiencies.
  • The overloaded assignment operator would behave differently from the built-in assignment operator, which could confuse others of our class.

In C++, when overloading the assignment operator, we must return a reference to the current object ( *this ) as it allows for assignment chaining, maintains consistency with built-in types, and avoids unnecessary object copying. By following these best practice, we can ensure that our overloaded operators are efficient, intuitive, and behave as expected, making our C++ programs more robust and maintainable.

author

Please Login to comment...

Similar reads.

  • C++-Operator Overloading

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Election 2024
  • Entertainment
  • Newsletters
  • Photography
  • AP Buyline Personal Finance
  • AP Buyline Shopping
  • Press Releases
  • Israel-Hamas War
  • Russia-Ukraine War
  • Global elections
  • Asia Pacific
  • Latin America
  • Middle East
  • Delegate Tracker
  • AP & Elections
  • 2024 Paris Olympic Games
  • Auto Racing
  • Movie reviews
  • Book reviews
  • Financial Markets
  • Business Highlights
  • Financial wellness
  • Artificial Intelligence
  • Social Media

Presented with rise in border crossings, Kamala Harris chose a long-term approach to the problem

Image

FILE - Vice President Kamala Harris stands in front of mountains during a news conference, June 25, 2021, at the airport after her tour of the U.S. Customs and Border Protection Central Processing Center in El Paso, Texas. (AP Photo/Jacquelyn Martin, File)

FILE - Vice President Kamala Harris, right, smiles as women speak to her about their businesses during a meeting with Guatemalan women entrepreneurs and innovators at the Universidad del Valle de Guatemala, June 7, 2021, in Guatemala City. (AP Photo/Jacquelyn Martin, File)

FILE - Vice President Kamala Harris walks to board Air Force Two to return to Washington, Jan. 27, 2022, in Palmerola, Honduras. (Erin Schaff/The New York Times via AP, Pool, File)

FILE - Vice President Kamala Harris speaks to the media, June 8, 2021, at the Sofitel Mexico City Reforma in Mexico City. (AP Photo/Jacquelyn Martin, File)

FILE - Vice President Kamala Harris and Mexican President Andrés Manuel López Obrador wave from the balcony of the Eisenhower Executive Office Building on the White House complex in Washington, Nov. 18, 2021. (AP Photo/Susan Walsh, File)

  • Copy Link copied

WASHINGTON (AP) — President Joe Biden , watching tens of thousands of migrants from Central America reach the U.S.-Mexico border just a few months into his administration, tapped his second-in-command to help address the influx — a decision that has exposed Vice President Kamala Harris to one of her biggest political liabilities.

In grappling with migration , Harris proceeded cautiously. She focused her time and prestige on boosting private investment in El Salvador, Honduras and Guatemala, the so-called Northern Triangle; her goal was to help create jobs to bolster economies and dissuade migrants from making the perilous journey to the United States.

It was a decidedly long-term — and limited — approach to a humanitarian crisis, and it has allowed Republicans to tie her to the broader fight over the border. While migration from the Northern Triangle ebbed, it surged from other nations, sparking an emergency at the U.S.-Mexico border, one that Republicans have aggressively sought to exploit at Harris’ expense.

What to know about the 2024 Election

  • Today’s news: Follow live updates from the campaign trail from the AP.
  • Ground Game: Sign up for AP’s weekly politics newsletter to get it in your inbox every Monday.
  • AP’s Role: The Associated Press is the most trusted source of information on election night, with a history of accuracy dating to 1848. Learn more.

A review of Harris’ work on immigration reveals a record that is more nuanced than the one presented by her critics or allies. It also provides insights into how Harris — who took over as the Democratic standard-bearer when Biden dropped out of the presidential race last month — might tackle one of the nation’s most vexing concerns.

Harris was never the “border czar,” or put in charge of border security or halting illegal border crossings, as former President Donald Trump, Republicans and even the occasional media outlet have claimed. Instead, she was tasked in March 2021 with tackling the “root causes” of migration from the Northern Triangle and pushing its leaders — along with Mexico’s — to enforce immigration laws, administration officials said.

Harris’ backers say she demonstrated leadership by leveraging her stature to win investments that might curb migration years down the road.

Image

Vice President Kamala Harris, right, smiles as women speak to her about their businesses during a meeting with Guatemalan women entrepreneurs and innovators at the Universidad del Valle de Guatemala, June 7, 2021, in Guatemala City. (AP Photo/Jacquelyn Martin, File)

“She felt — and I think she was right — that what she could do the most was help basically lead the effort to draw in investment, using the confidence that a relationship with the White House would give to investors,” said Ricardo Zúniga, a former State Department official who specialized in the Northern Triangle and who traveled with Harris to the region.

Critics contend that she could have done far more but chose a less risky path, ensuring the problem only worsened.

“She was like, ‘nope, I’m just root causes,’’” said Mark Krikorian, executive director of the Center for Immigration Studies, which advocates for less immigration. “Even if it worked, it’s the sort of thing that takes generations, not one term.”

He also said there was no evidence that Harris pushed Mexico and the Northern Triangle nations to enforce immigration laws.

Harris has defended her work, and her campaign began running a television ad Friday that said Harris as president would “hire thousands more border agents and crack down on fentanyl and human trafficking.” Democrats have also blasted Trump for helping tank a bipartisan immigration bill earlier this year that would have increased funding for border security, including the hiring of new Customs and Border Protection personnel.

Trump “has been talking a big game on securing the border, but he does not walk the walk,” the vice president said last month in Atlanta . Later, she added, “Donald Trump does not care about border security. He only cares about himself.”

Image

Immigration becomes a big political issue

Immigration has long been an issue that motivates Trump and his base of supporters, and polls show it is among the most important issues on the minds of voters. As a presidential candidate in 2016, Trump said he would build a wall along the border between the United States and Mexico and get Mexico to pay for it. Trump was not able to complete the project, and Mexico did not fund the part of the barrier that was constructed. The former president also used explosive language to describe immigrants, launching his campaign by suggesting Mexico was sending its “rapists” and criminals to the United States.

While in office, Trump sought to tightly restrict asylum, which was challenged in the courts. This time around, Trump has promised to oversee a “mass deportation” of migrants who have committed crimes in the United States.

Image

Vice President Kamala Harris walks to board Air Force Two to return to Washington, Jan. 27, 2022, in Palmerola, Honduras. (Erin Schaff/The New York Times via AP, Pool, File)

Migration numbers have spiked and dropped during both presidencies. Border Patrol arrests on the southern border fell in Trump’s first year in office, then shot back up his next two, rising to more than 850,000 in 2019. The numbers plunged in 2020 during the coronavirus pandemic before rising even higher during Biden’s presidency, reaching a peak of more than 250,000 encounters in December 2023, before falling below 84,000 in June of 2024, federal statistics show.

When Biden took office, he reversed dozens of Trump’s moves on immigration even as apprehension numbers began to rise.

Harris was put in a ‘difficult spot’

Harris received the migration assignment when border crossings were rising, garnering considerable attention and leading to bipartisan calls for action.

Chris Newman, an immigration rights advocate in Los Angeles, said Harris was put in a difficult spot.

“She was tasked with developing a long-term policy framework rather than creating a short-term political performance project,” said Newman, the legal director of the National Day Laborer Organizing Network.

Biden and Harris had taken office only two months before, and Harris was under pressure to build her policy portfolio. When he was vice president, Biden had taken on a similar role on immigration. In 2021, though, Harris was dealing with an especially challenging situation given the lack of governing partners in the region. El Salvador’s new president, Nayib Bukele, had a fraught relationship with the administration due to human rights questions raised by his crackdown on crime in his nation. The man who was then president of Honduras has since been convicted of drug trafficking.

The headaches for Harris began almost immediately, validating the concerns of some on her team that it was a no-win assignment.

Harris traveled to Mexico and Guatemala in June 2021, where she defended the fact she had not been to the U.S.-Mexico border during an interview with NBC’s Lester Holt by saying she hadn’t “been to Europe. And I mean, I don’t … understand the point that you’re making.”

She also drew criticism on that trip for warning migrants bluntly: “Don’t come” to the U.S.

Harris decided to focus on bringing private investment to the region, tapping into a network of business and nonprofit executives and using the prestige of the White House to signal the Biden administration was backing this effort.

The work linked multinational companies — like Visa, Nestle and Meta — with smaller nonprofits and Latin American businesses, all of which pledged to increase their investments or bolster their work with at-risk communities.

Image

Vice President Kamala Harris and Mexican President Andrés Manuel López Obrador wave from the balcony of the Eisenhower Executive Office Building on the White House complex in Washington, Nov. 18, 2021. (AP Photo/Susan Walsh, File)

Focused on private investment

The Associated Press contacted all the nearly two dozen companies the White House touted as participants in the outreach effort. Some, like AgroAmerica, a sustainable food corporation, that pledged to invest more than $100 million in six new projects, reported their work had begun and they were on track to meet their investment goals. Others, including Columbia Sportswear Company, said they would likely surpass their pledges.

Most companies, however, either declined to comment or did not respond when asked about their efforts.

The vice president’s office has said Harris’ efforts have generated more than $5.2 billion in investment promises. In an illustration of how long it takes the promises to translate into concrete spending, the State Department reported that companies have plowed nearly $1.3 billion in the region as of June 2024, the bulk of it in Guatemala and Honduras.

“We are on track to exceed our commitments,” Peter Bragdon, a top executive at Columbia Sportswear Company, said of their promise to purchase up to $200 million in products from the region. That pledge would create nearly 7,000 jobs over five years, the company said. The executive called Harris’ efforts a “work in progress” but “a smart approach.”

Katie Tobin, who worked as the top migration adviser at the National Security Council for three years, credited Harris’ focus with spurring investment in reducing these numbers, arguing that Harris “was able to leverage her credibility” and the power of the White House to persuade companies to invest in “a risky investment environment.”

“That was very much Kamala Harris,” she added. “I have never seen something like that done before in this space and it made a real impact.”

Republican Sen. Rick Scott of Florida, a sharp critic of Harris, said the vice president and White House were taking credit for investments that would have been made anyway.

The companies are “not doing it because someone asked them to,” said Scott, who co-founded a major medical company. “They’re doing it because it makes economic sense.”

Addressed corruption

Harris also sought to address endemic corruption that has fueled migration from Central America. Before her 2021 trip to Guatemala, Harris met with a group of exiled Guatemalan prosecutors and judges in Washington.

Among them was Thelma Aldana, a former chief prosecutor who fled her country after what she said were politically motivated corruption charges.

“I came out of it convinced that she has a genuine interest in seeing things change in Central America,” Aldana said.

The vice president also deserves credit for helping stop Guatemala’s former president, Alejandro Giammattei, from overturning the 2023 election of his successor, Bernardo Arévalo, according to Luis Von Ahn, a U.S.-based technology entrepreneur from Guatemala.

“Giammattei didn’t want to leave power, the administration of Kamala Harris came and told him ’stop (messing) around,’” said Von Ahn, the founder of the language app Duolingo. “That’s a big help to Guatemala. If an extremely corrupt president doesn’t want to leave it’s terrible and (his exit) lets us be a better country.”

Verdict is out on Harris’ approach

While the Harris campaign and White House have pointed to statistics that show migration from Northern Triangle countries has dropped substantially since early 2021, there is debate over what is responsible for that drop.

Sen. Chris Murphy, D-Conn., said Harris and the administration deserve credit for the reduction because their efforts “worked.”

Independent analysts, however, said they were skeptical that Harris’ approach was responsible for the dip. They said the decrease was likely driven by regional factors, including the ascension of El Salvador’s new president and his aggressive drive to combat violent crime. His government reported a 70% drop in homicides in 2023.

Julia Gelatt, associate director of the Migration Policy Institute in Washington, said investment can take years to alter migration patterns — if it ever does.

“Even a whole lot of economic development doesn’t curb immigration in the way countries hope it will,” Gelatt said.

Riccardi reported from Denver. Associated Press writer Sonia Pérez D. in Guatemala City contributed to this story.

Image

IMAGES

  1. Assignment Operators in C

    reference assignment in c

  2. How to Return by Reference in C++?

    reference assignment in c

  3. References in C++

    reference assignment in c

  4. Pointer Expressions in C with Examples

    reference assignment in c

  5. C programming +=

    reference assignment in c

  6. Assignment Operator in C Programming

    reference assignment in c

COMMENTS

  1. c++

    Why can I assign a new value to a reference, and how can I make a reference refer to something else? Asked 12 years, 11 months ago Modified 3 years, 11 months ago Viewed 87k times

  2. Pass By Reference In C

    Passing by reference is a technique for passing parameters to a function. It is also known as call by reference, call by pointers, and pass by pointers. In this article, we will discuss this technique and how to implement it in our C program.

  3. Reference declaration

    A reference variable declaration is any simple declaration whose declarator has the form. &attr  (optional)declarator. (1) &&attr  (optional)declarator. (2) (since C++11) 1)Lvalue reference declarator: the declaration S& D; declares D as an lvalue reference to the type determined by decl-specifier-seqS. 2)Rvalue reference declarator: the ...

  4. References in C++

    Also, we can define a reference variable as a type of variable that can act as a reference to another variable. '&' is used for signifying the address of a variable or any memory. Variables associated with reference variables can be accessed either by its name or by the reference variable associated with it. Prerequisite: Pointers in C++ ...

  5. References, C++ FAQ

    References ¶ Δ Contents of this section: What is a reference? What happens if you assign to a reference? What happens if you return a reference? What does object.method1().method2() mean? How can you reseat a reference to make it refer to a different object? Why does C++ have both pointers and references? When should I use references, and when should I use pointers? What does it mean that a ...

  6. Assignment Expressions (GNU C Language Manual)

    An assignment in C is an expression because it has a value; we call it an assignment expression. A simple assignment looks like. lvalue = value-to-store. 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 ...

  7. Call by Value and Call by Reference in C

    Call by reference. In this method addresses of the actual arguments are copied and then assigned to the corresponding formal arguments. Now formal and actual arguments both points to the same data (because they contain the same address). As a result, any changes made by called function also affect the actual arguments. Let's take some examples:

  8. Assignment operators

    for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast.

  9. Function Call by Reference in C

    Function Call by Reference in C - There are two ways in which a function can be called: (a) Call by Value and (b) Call by Reference. In this chapter, we will explain the mechanism of calling a function by reference.

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

  11. Assignment Operators in C

    Assignment Operators in C - In C language, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable, or an expression.

  12. Reference and Value Semantics, C++ FAQ

    C++ gives you the choice: use the assignment operator to copy the value (copy/value semantics), or use a pointer-copy to copy a pointer (reference semantics). C++ allows you to override the assignment operator to do anything your heart desires, however the default (and most common) choice is to copy the value.

  13. Copy constructors and copy assignment operators (C++)

    Use an assignment operator operator= that returns a reference to the class type and takes one parameter that's passed by const reference—for example ClassName& operator=(const ClassName& x);. Use the copy constructor. If you don't declare a copy constructor, the compiler generates a member-wise copy constructor for you.

  14. 12.3

    An lvalue reference (commonly just called a reference since prior to C++11 there was only one type of reference) acts as an alias for an existing lvalue (such as a variable). To declare an lvalue reference type, we use an ampersand (&) in the type declaration: int // a normal int type int& // an lvalue reference to an int object double& // an ...

  15. Assigning reference to a variable in C++

    8 My question is why it is possible to assign reference to a variable that is not declared as reference?

  16. Default Assignment Operator and References in C++

    Learn about the default assignment operator and references in C++ with well-explained articles, quizzes, and programming practice.

  17. How to Use C++ Reference Variables (C++ Reference Vs Pointer Example)

    When compared to C, C++ has some very unique features that come in very handy. For example, the concept of references. In this tutorial, we will discuss the reference concept through some practical examples.

  18. Red Sox reliever taking next step in rehab from Tommy John

    The Boston Red Sox have been in desperate need of some help in the bullpen over the last month or so, as the two relievers they added at the deadline (Lucas Sims and Luis Garcia) haven't provided ...

  19. Pitcher Elects Free Agency Rather Than Staying in Padres' Organization

    Pitcher Carl Edwards Jr. cleared waivers and elected free agency. Prior to being designated for assignment on Monday, he had one major league appearance this season with the San Diego Padres.

  20. Scott Peterson denies killing his pregnant wife nearly two ...

    Nearly 20 years after Scott Peterson was convicted of murder in the deaths of his wife and their unborn son - and months after the Los Angeles Innocence Project took up his case - he is ...

  21. IEEE 802.1X VLAN Assignment

    Bias-Free Language. The documentation set for this product strives to use bias-free language. For the purposes of this documentation set, bias-free is defined as language that does not imply discrimination based on age, disability, gender, racial identity, ethnic identity, sexual orientation, socioeconomic status, and intersectionality.

  22. KB5042320: Windows Recovery Environment update for Windows 10, version

    IMPORTANT This update will not be offered if your Windows Recovery Environment (WinRE) meets any of the following conditions: If the WinRE recovery partition does not have sufficient free space, see the NOTE in the "Summary" section. The note provides instructions about how to increase the available free space in the WinRE recovery partition.

  23. Nvd

    References to Advisories, Solutions, and Tools. By selecting these links, you will be leaving NIST webspace. We have provided these links to other web sites because they may have information that would be of interest to you. No inferences should be drawn on account of other sites being referenced, or not, from this page.

  24. Assignment Operators 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.

  25. Nvd

    References to Advisories, Solutions, and Tools. By selecting these links, you will be leaving NIST webspace. We have provided these links to other web sites because they may have information that would be of interest to you. No inferences should be drawn on account of other sites being referenced, or not, from this page.

  26. c++

    In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the new object?

  27. How to cite ChatGPT

    References for a number of common sources, such as journal articles and books, do not include bracketed descriptions, but things outside of the typical peer-reviewed system often do. In the case of a reference for ChatGPT, provide the descriptor "Large language model" in square brackets. OpenAI describes ChatGPT-4 as a "large multimodal ...

  28. PDF 7th edition Common Reference Examples Guide

    Common Reference Examples Guide This guide contains examples of common types of APA Style references. Section numbers indicate where to find the examples in the Publication Manual of the American Psychological Association (7th ed.). More information on references and reference examples are in Chapters 9 and 10 of the Publication

  29. Why Assignment Operator Overloading Must Return Reference?

    In C++, assignment operations can be chained together. For example: A a, b, c; a = b = c; To support this chaining, the assignment operator must return a reference to the object being assigned. This allows the operation b = c to return b, enabling a = b to work as expected. 2. Consistency with Built-in Types. For built-in types, the assignment ...

  30. Election 2024: Harris chose a long-term approach to deal with border

    WASHINGTON (AP) — President Joe Biden, watching tens of thousands of migrants from Central America reach the U.S.-Mexico border just a few months into his administration, tapped his second-in-command to help address the influx — a decision that has exposed Vice President Kamala Harris to one of her biggest political liabilities.. In grappling with migration, Harris proceeded cautiously.