cppreference.com

Assignment operators.

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

[ edit ] Simple assignment

The simple assignment operator expressions have the form

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

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

rhs and lhs must satisfy one of the following:

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

[ edit ] Notes

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

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

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

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

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

[ edit ] Compound assignment

The compound assignment operator expressions have the form

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

[ edit ] References

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

[ edit ] See Also

Operator precedence

[ edit ] See also

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

Powered by MediaWiki

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples

Relationship Between Arrays and Pointers

C Pass Addresses and Pointers

C structs and Pointers

  • Access Array Elements Using Pointer

C Dynamic Memory Allocation

  • C Array and Pointer Examples

Pointers are powerful features of C and C++ programming. Before we learn pointers, let's learn about addresses in C programming.

  • Address in C

If you have a variable var in your program, &var will give you its address in the memory.

We have used address numerous times while using the scanf() function.

Here, the value entered by the user is stored in the address of var variable. Let's take a working example.

Note: You will probably get a different address when you run the above code.

Pointers (pointer variables) are special variables that are used to store addresses rather than values.

Pointer Syntax

Here is how we can declare pointers.

Here, we have declared a pointer p of int type.

You can also declare pointers in these ways.

Let's take another example of declaring pointers.

Here, we have declared a pointer p1 and a normal variable p2 .

  • Assigning addresses to Pointers

Let's take an example.

Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.

Get Value of Thing Pointed by Pointers

To get the value of the thing pointed by the pointers, we use the * operator. For example:

Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we used *pc .

Note: In the above example, pc is a pointer, not *pc . You cannot and should not do something like *pc = &c ;

By the way, * is called the dereference operator (when working with pointers). It operates on a pointer and gives the value stored in that pointer.

  • Changing Value Pointed by Pointers

We have assigned the address of c to the pc pointer.

Then, we changed the value of c to 1. Since pc and the address of c is the same, *pc gives us 1.

Let's take another example.

Then, we changed *pc to 1 using *pc = 1; . Since pc and the address of c is the same, c will be equal to 1.

Let's take one more example.

Initially, the address of c is assigned to the pc pointer using pc = &c; . Since c is 5, *pc gives us 5.

Then, the address of d is assigned to the pc pointer using pc = &d; . Since d is -15, *pc gives us -15.

  • Example: Working of Pointers

Let's take a working example.

Explanation of the program

A pointer variable and a normal variable is created.

Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c . Then,

Here's an example of pointer syntax beginners often find confusing.

Why didn't we get an error when using int *p = &c; ?

It's because

is equivalent to

In both cases, we are creating a pointer p (not *p ) and assigning &c to it.

To avoid this confusion, we can use the statement like this:

Now you know what pointers are, you will learn how pointers are related to arrays in the next tutorial.

Table of Contents

  • What is a pointer?
  • Common Mistakes

Sorry about that.

Related Tutorials

DEV Community

DEV Community

AbdulKarim

Posted on Oct 29, 2023

How C-Pointers Works: A Step-by-Step Beginner's Tutorial

In this comprehensive C Pointers tutorial, my primary goal is to guide you through the fundamentals of C pointers from the ground up. By the end of this tutorial, you will have gained an in-depth understanding of the following fundamental topics:

  • What is a Pointer?
  • How Data is Stored in Memory?
  • Storing Memory Addresses using Pointers

Accessing Data through Pointers

  • Pointer Arithmetic
  • Pointer to Pointer (Double Pointers)
  • Passing Pointers as Function Arguments

Arrays of Pointers

Null pointers, prerequisite:.

To grasp pointers effectively, you should be comfortable with basic C programming concepts, including variables, data types, functions, loops, and conditional statements. This familiarity with C programming forms the foundation for understanding how pointers work within the language. Once you have a solid grasp of these fundamental concepts, you can confidently delve into the intricacies of C pointers.

What is a pointer?

A pointer serves as a reference that holds the memory location of another variable. This memory address allows us to access the value stored at that location in the memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory

Pointers can be a challenging concept for beginners to grasp, but in this tutorial, I'll explain them using real-life analogies to make the concept clearer. However, Before delving into pointers and their workings, it's important to understand the concept of a memory address.

A memory address is a unique identifier that points to a specific location in a computer's memory. Think of it like a street address for data stored in your computer's RAM (Random Access Memory). Just as a street address tells you where a particular house is located in the physical world, a memory address tells the computer where a specific piece of information or data is stored in its memory.

Take a look at the image below for a better understanding:

Block of memory

In this illustration, each block represents one byte of memory. It's important to note that every byte of memory has a unique address. To make it easier to understand, I've represented the addresses in decimal notation, but computers actually store these addresses using hexadecimal values. Hexadecimal is a base-16 numbering system commonly used in computing to represent memory addresses and other low-level data. It's essential to be aware of this representation when working with memory-related concepts in computer programming

How data is stored in the memory:

Every piece of data in your computer, whether it's a number, a character, or a program instruction, is stored at a specific memory address. The amount of space reserved for each data type can vary, and it is typically measured in bytes (where 1 byte equals 8 bits, with each bit representing either 0 or 1). The specific sizes of data types also depend on the computer architecture you are using. For instance, on most 64-bit Linux machines, you'll find the following typical sizes for common data types: char = 1 byte int = 4 bytes float = 4 bytes double = 8 bytes These sizes define how much memory each data type occupies and are crucial for memory management and efficient data representation in computer systems.

You can use the sizeof operator to determine the size of data types on your computer. example:

In this example: sizeof(char) returns the size of the char data type in bytes. sizeof(int) returns the size of the int data type in bytes. sizeof(float) returns the size of the float data type in bytes. sizeof(double) returns the size of the double data type in bytes. When you run this code, it will print the sizes of these data types on your specific computer, allowing you to see the actual sizes used by your system.

When you declare a variable, the computer allocates a specific amount of memory space corresponding to the chosen data type. For instance, when you declare a variable of type char, the computer reserves 1 byte of memory because the size of the 'char' data type is conventionally 1 byte.

address of char n

In this example, we declare a variable n of type char without assigning it a specific value. The memory address allocated for the n variable is 106 . This address, 106 , is where the computer will store the char variable n, but since we haven't assigned it a value yet, the content of this memory location may initially contain an unpredictable or uninitialized value.

When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n. When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n.

address of cahr n = c

As mentioned earlier, a byte can only store numerical values. When we store the letter 'C' in a byte, the byte actually holds the ASCII code for 'C,' which is 67. In computer memory, characters are represented using their corresponding ASCII codes. So, in memory, the character 'C' is stored as the numerical value 67. Here's how it looks in memory

Ascii code of c

Since integers are typically stored within four bytes of memory, let's consider the same example with an int variable. In this scenario, the memory structure would appear as follows:

add. of int t

In this example, the memory address where the variable t is stored is 121. An int variable like “t” typically uses four consecutive memory addresses, such as 121, 122, 123, and 124. The starting address, in this case, 121, represents the location of the first byte of the int, and the subsequent addresses sequentially represent the following bytes that collectively store the complete int value.

If you want to know the memory address of a variable in a program, you can use the 'address of' unary operator, often denoted as the '&' operator. This operator allows you to access the specific memory location where a variable is stored.

When you run the following program on your computer: It will provide you with specific memory addresses for the variables c and n. However, each time you rerun the program, it might allocate new memory addresses for these variables. It's important to understand that while you can determine the memory address of a variable using the & operator, the exact memory location where a variable is stored is typically managed by the system and the compiler. As a programmer, you cannot directly control or assign a specific memory location for a variable. Instead, memory allocation and management are tasks handled by the system and the compiler.

Storing memory address using pointers

As mentioned earlier, a pointer is a variable that stores the memory address of another variable. This memory address allows us to access the value stored at that location in memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory.

Now, let's begin by declaring and initializing pointers. This step is essential because it sets up the pointer to hold a specific memory address, enabling us to interact with the data stored at that location.

Declaring Pointers: To declare a pointer, you specify the data type it points to, followed by an asterisk (*), and then the pointer's name. For example:

Here, we've declared a pointer named ptr that can point to integers.

Memory of Declaring an integer pointer

The size of pointers on 64-bit systems is usually 8 bytes (64 bits). To determine the pointer size on your system, you can use the sizeof operator:

Initializing Pointers: Once you've declared a pointer, you typically initialize it with the memory address it should point to. Once again, To obtain the memory address of a variable, you can employ the address-of operator (&). For instance:

In this program:

We declare an integer variable x and initialize it with the value 10. This line creates a variable x in memory and assigns the value 10 to it.

ptr

We declare an integer pointer ptr using the int *ptr syntax. This line tells the compiler that ptr will be used to store the memory address of an integer variable.

pointrt to ptr

We initialize the pointer ptr with the memory address of the variable x . This is achieved with the line ptr = &x; . The & operator retrieves the memory address of x, and this address is stored in the pointer ptr .

address of variable x

Dereferencing Pointers: To access the data that a pointer is pointing to, you need to dereference the pointer. Dereferencing a pointer means accessing the value stored at the memory address that the pointer points to. In C, you can think of pointers as variables that store memory addresses rather than actual values. To get the actual value (data) stored at that memory address, you need to dereference the pointer.

Dereferencing is done using the asterisk (*) operator. Here's an example:

It looks like this in the memory: int x = 10; variable 'x' stores the value 10:

var X

int *ptr = &x; Now, the pointer 'ptr' point to the address of 'x':

Pointer to X

int value = *ptr; Dereference 'ptr' to get the value stored at the address it points to:

pointer value is 10

Reading and Modifying Data: Pointers allow you to not only read but also modify data indirectly:

Note: The asterisk is a versatile symbol with different meanings depending on where it's used in your C program, for example: Declaration: When used during variable declaration, the asterisk (*) indicates that a variable is a pointer to a specific data type. For example: int *ptr; declares 'ptr' as a pointer to an integer.

Dereferencing: Inside your code, the asterisk (*) in front of a pointer variable is used to access the value stored at the memory address pointed to by the pointer. For example: int value = *ptr; retrieves the value at the address 'ptr' points to.

Pointer Arithmetic:

Pointer arithmetic is the practice of performing mathematical operations on pointers in C. This allows you to navigate through arrays, structures, and dynamically allocated memory. You can increment or decrement pointers, add or subtract integers from them, and compare them. It's a powerful tool for efficient data manipulation, but it should be used carefully to avoid memory-related issues.

Incrementing a Pointer:

Now, this program is how it looks in the memory: int arr[4] = {10, 20, 30, 40};

int arr

This behavior is a key aspect of pointer arithmetic. When you add an integer to a pointer, it moves to the memory location of the element at the specified index, allowing you to efficiently access and manipulate elements within the array. It's worth noting that you can use pointer arithmetic to access elements in any position within the array, making it a powerful technique for working with arrays of data. Now, let's print the memory addresses of the elements in the array from our previous program.

If you observe the last two digits of the first address is 40, and the second one is 44. You might be wondering why it's not 40 and 41. This is because we're working with an integer array, and in most systems, the size of an int data type is 4 bytes. Therefore, the addresses are incremented in steps of 4. The first address shows 40, the second 44, and the third one 48

Decrementing a Pointer Decrement (--) a pointer variable, which makes it point to the previous element in an array. For example, ptr-- moves it to the previous one. For example:

Explanation:

We have an integer array arr with 5 elements, and we initialize a pointer ptr to point to the fourth element (value 40) using &arr[3].

Then, we decrement the pointer ptr by one with the statement ptr--. This moves the pointer to the previous memory location, which now points to the third element (value 30).

Finally, we print the value pointed to by the decremented pointer using *ptr, which gives us the value 30.

In this program, we demonstrate how decrementing a pointer moves it to the previous memory location in the array, allowing you to access and manipulate the previous element.

Pointer to pointer

Pointers to pointers, or double pointers, are variables that store the address of another pointer. In essence, they add another level of indirection. These are commonly used when you need to modify the pointer itself or work with multi-dimensional arrays.

To declare and initialize a pointer to a pointer, you need to add an extra asterisk (*) compared to a regular pointer. Let's go through an example:

In this example, ptr2 is a pointer to a pointer. It points to the memory location where the address of x is stored (which is ptr1 ).

pointer to poiter

The below program will show you how to print the value of x through pointer to pointer

In this program, we first explain that it prints the value of x using a regular variable, a pointer, and a pointer to a pointer. We then print the memory addresses of x , ptr1 , and ptr2 .

Passing Pointers as Function Arguments:

In C, you can pass pointers as function arguments. This allows you to manipulate the original data directly, as opposed to working with a copy of the data, as you would with regular variables. Here's how it works:

How to Declare and Define Functions that Take Pointer Arguments: In your function declaration and definition, you specify that you're passing a pointer by using the * operator after the data type. For example:

In the above function, we declare ptr as a pointer to an integer. This means it can store the memory address of an integer variable.

Why Would You Pass Pointers to Functions?

Passing pointers to functions allows you to:

  • Modify the original data directly within the function.
  • Avoid making a copy of the data, which can be more memory-efficient.
  • Share data between different parts of your program efficiently.

This concept is especially important when working with large data structures or when you need to return multiple values from a function.

Call by Value vs. Call by Reference:

Understanding how data is passed to functions is crucial when working with pointers. there are two common ways that data can be passed to functions: call by value and call by reference.

Call by Value:

When you pass data by value, a copy of the original data is created inside the function. Any modifications to this copy do not affect the original data outside of the function. This is the default behavior for most data types when you don't use pointers.

Call by Reference (Using Pointers):

When you pass data by reference, you're actually passing a pointer to the original data's memory location. This means any changes made within the function will directly affect the original data outside the function. This is achieved by passing pointers as function arguments, making it call by reference. Using pointers as function arguments allows you to achieve call by reference behavior, which is particularly useful when you want to modify the original data inside a function and have those changes reflected outside the function.

Let's dive into some code examples to illustrate how pointers work as function arguments. We'll start with a simple example to demonstrate passing a pointer to a function and modifying the original data.

Consider this example:

In this code, we define a function modifyValue that takes a pointer to an integer. We pass the address of the variable num to this function, and it doubles the value stored in num directly.

This is a simple demonstration of passing a pointer to modify a variable's value. Pointers allow you to work with the original data efficiently.

An array of pointers is essentially an array where each element is a pointer. These pointers can point to different data types (int, char, etc.), providing flexibility and efficiency in managing memory.

How to Declare an Array of Pointers? To declare an array of pointers, you specify the type of data the pointers will point to, followed by square brackets to indicate it's an array, and then the variable name. For example:

Initializing an Array of Pointers You can initialize an array of pointers to each element to point to a specific value, For example:

How to Access Elements Through an Array of Pointers? To access elements through an array of pointers, you can use the pointer notation. For example:

This program demonstrates how to access and print the values pointed to by the pointers in the array.

A NULL pointer is a pointer that lacks a reference to a valid memory location. It's typically used to indicate that a pointer doesn't have a specific memory address assigned, often serving as a placeholder or default value for pointers.

Here's a code example that demonstrates the use of a NULL pointer:

In this example, we declare a pointer ptr and explicitly initialize it with the value NULL. We then use an if statement to check if the pointer is NULL. Since it is, the program will print "The pointer is NULL." This illustrates how NULL pointers are commonly used to check if a pointer has been initialized or assigned a valid memory address.

conclusion:

You've embarked on a comprehensive journey through the intricacies of C pointers. You've learned how pointers store memory addresses, enable data access, facilitate pointer arithmetic, and how they can be used with arrays and functions. Additionally, you've explored the significance of NULL pointers.

By completing this tutorial, you've equipped yourself with a robust understanding of pointers in C. You can now confidently navigate memory, manipulate data efficiently, and harness the power of pointers in your programming projects. These skills will be invaluable as you advance in your coding endeavors. Congratulations on your accomplishment, and keep coding with confidence!

Reference: C - Pointers - Tutorials Point

Pointers in C: A One-Stop Solution for Using C Pointers - simplilearn

Top comments (3)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

imperiald profile image

  • Joined Jan 7, 2024

Love your way to write articles, could you add an article for, .o files, .h files, lists and makefile? Thank you in advance!

cocomelonjuice profile image

  • Joined Nov 4, 2023

Great post. Thank you so much for this.

koderkareem profile image

Thank you for your kind words! I'm thrilled to hear that you enjoyed the article. Your feedback means a lot to me. If you have any questions or if there's a specific topic you'd like to see in future posts, feel free to let me know. Thanks again for your support

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

ant_f_dev profile image

Dynamically Change PNG Icon Colours for Mouseover Effects

Anthony Fung - Mar 6

mgeovany profile image

Como configurar Prettier y no morir en el intento, extensiones de VSCode que te ayudarán 🤯

Geovany - Mar 6

jlxfd profile image

This isn't the Productivity Post You Want but Need to Understand

Julia Alexis Diaz - Apr 3

ssukhpinder profile image

Day 16 of 30-Day .NET Challenge: In-Memory Caching

Sukhpinder Singh - Apr 4

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

CHAPTER 1: What is a pointer?

  • C++ Language
  • Ascii Codes
  • Boolean Operations
  • Numerical Bases

Introduction

Basics of c++.

  • Structure of a program
  • Variables and types
  • Basic Input/Output

Program structure

  • Statements and flow control
  • Overloads and templates
  • Name visibility

Compound data types

  • Character sequences
  • Dynamic memory
  • Data structures
  • Other data types
  • Classes (I)
  • Classes (II)
  • Special members
  • Friendship and inheritance
  • Polymorphism

Other language features

  • Type conversions
  • Preprocessor directives

Standard library

  • Input/output with files

Address-of operator (&)

c assignment operator pointer

Dereference operator (*)

c assignment operator pointer

  • & is the address-of operator , and can be read simply as "address of"
  • * is the dereference operator , and can be read as "value pointed to by"

Declaring pointers

Pointers and arrays, pointer initialization, pointer arithmetics.

c assignment operator pointer

Pointers and const

Pointers and string literals.

c assignment operator pointer

Pointers to pointers

c assignment operator pointer

  • c is of type char** and a value of 8092
  • *c is of type char* and a value of 7230
  • **c is of type char and a value of 'z'

void pointers

Invalid pointers and null pointers, pointers to functions.

CProgramming Tutorial

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

Assignment Operators in C

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

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

Simple assignment operator (=)

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

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

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

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

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

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

Augmented assignment operators

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

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

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

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

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

Learn C++

21.12 — Overloading the assignment operator

The copy assignment operator (operator=) is used to copy values from one object to another already existing object .

Related content

As of C++11, C++ also supports “Move assignment”. We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

Copy assignment vs Copy constructor

The purpose of the copy constructor and the copy assignment operator are almost equivalent -- both copy one object to another. However, the copy constructor initializes new objects, whereas the assignment operator replaces the contents of existing objects.

The difference between the copy constructor and the copy assignment operator causes a lot of confusion for new programmers, but it’s really not all that difficult. Summarizing:

  • If a new object has to be created before the copying can occur, the copy constructor is used (note: this includes passing or returning objects by value).
  • If a new object does not have to be created before the copying can occur, the assignment operator is used.

Overloading the assignment operator

Overloading the copy assignment operator (operator=) is fairly straightforward, with one specific caveat that we’ll get to. The copy assignment operator must be overloaded as a member function.

This prints:

This should all be pretty straightforward by now. Our overloaded operator= returns *this, so that we can chain multiple assignments together:

Issues due to self-assignment

Here’s where things start to get a little more interesting. C++ allows self-assignment:

This will call f1.operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves. In this particular example, the self-assignment causes each member to be assigned to itself, which has no overall impact, other than wasting time. In most cases, a self-assignment doesn’t need to do anything at all!

However, in cases where an assignment operator needs to dynamically assign memory, self-assignment can actually be dangerous:

First, run the program as it is. You’ll see that the program prints “Alex” as it should.

Now run the following program:

You’ll probably get garbage output. What happened?

Consider what happens in the overloaded operator= when the implicit object AND the passed in parameter (str) are both variable alex. In this case, m_data is the same as str.m_data. The first thing that happens is that the function checks to see if the implicit object already has a string. If so, it needs to delete it, so we don’t end up with a memory leak. In this case, m_data is allocated, so the function deletes m_data. But because str is the same as *this, the string that we wanted to copy has been deleted and m_data (and str.m_data) are dangling.

Later on, we allocate new memory to m_data (and str.m_data). So when we subsequently copy the data from str.m_data into m_data, we’re copying garbage, because str.m_data was never initialized.

Detecting and handling self-assignment

Fortunately, we can detect when self-assignment occurs. Here’s an updated implementation of our overloaded operator= for the MyString class:

By checking if the address of our implicit object is the same as the address of the object being passed in as a parameter, we can have our assignment operator just return immediately without doing any other work.

Because this is just a pointer comparison, it should be fast, and does not require operator== to be overloaded.

When not to handle self-assignment

Typically the self-assignment check is skipped for copy constructors. Because the object being copy constructed is newly created, the only case where the newly created object can be equal to the object being copied is when you try to initialize a newly defined object with itself:

In such cases, your compiler should warn you that c is an uninitialized variable.

Second, the self-assignment check may be omitted in classes that can naturally handle self-assignment. Consider this Fraction class assignment operator that has a self-assignment guard:

If the self-assignment guard did not exist, this function would still operate correctly during a self-assignment (because all of the operations done by the function can handle self-assignment properly).

Because self-assignment is a rare event, some prominent C++ gurus recommend omitting the self-assignment guard even in classes that would benefit from it. We do not recommend this, as we believe it’s a better practice to code defensively and then selectively optimize later.

The copy and swap idiom

A better way to handle self-assignment issues is via what’s called the copy and swap idiom. There’s a great writeup of how this idiom works on Stack Overflow .

The implicit copy assignment operator

Unlike other operators, the compiler will provide an implicit public copy assignment operator for your class if you do not provide a user-defined one. This assignment operator does memberwise assignment (which is essentially the same as the memberwise initialization that default copy constructors do).

Just like other constructors and operators, you can prevent assignments from being made by making your copy assignment operator private or using the delete keyword:

Note that if your class has const members, the compiler will instead define the implicit operator= as deleted. This is because const members can’t be assigned, so the compiler will assume your class should not be assignable.

If you want a class with const members to be assignable (for all members that aren’t const), you will need to explicitly overload operator= and manually assign each non-const member.

guest

  • Utility Programs

MYCPLUS - C and C++ Programming Resources

  • C Tutorials
  • C++ Tutorials
  • Source Code
  • Mobile Tech

Select Page

  • Operators in C Programming

Posted by M. Saqib | Updated Feb 25, 2024 | C Programming: Different Articles on C Programming |

Operators in C Programming

In C Programming, operators are symbols or keywords used to perform operations on values and variables. These are fundamental to performing various operations in C programming and are essential for building complex algorithms and programs. We can use operators to perform a wide range of tasks, including arithmetic calculations, logical operations, and comparisons.

Table of Contents

Increment or decrement operators (++ and –), pointer operators (*, & and ->), logical not operator (), assignment operators ( =, +=, -=, *=, /=, %= ).

  • Other Assignment Operators (>>=, <<=, &=, |= and ^=)

Arithmetic Operators (+, -, /, * and %)

Relational or comparison operators (==, =, >, <, >= and <=), using both assignment (=) and comparison (==) operators together, logical operators ( , && and ||), bit-wise operators (~, &, |, ^, >> and <<), conditional operator ( :), comma operator ( , ), infographics – operators diagram.

There are three major groups of operators in C which are Unary Operators, Binary Operators and Ternary Operators.

Unary Operators

In C programming, a unary operator is an operator that operates on only one operand, either to its left or right. These operators perform various operations such as incrementing or decrementing a value, negating a value, or obtaining the address of a variable.

The unary ++ and — operators increment or decrements the value in a variable. There are “pre” and “post” variants for both operators which do slightly different things (explained below)

In C, pointer operators are operators that are used in conjunction with pointers. There are several pointer operators in C, including:

  • Address-of operator ( & ) : Returns the memory address of a variable. When used with a variable, the & operator returns the address of the variable in memory.
  • Dereference operator ( * ) : Accesses the value stored at a memory address. When used with a pointer, the * operator returns the value stored at the address pointed to by the pointer.
  • Indirection operator ( -> ) : Accesses a member of a structure through a pointer. The -> operator is used to access members of a structure when a pointer to the structure is used.

The logical NOT operator (!) is a unary operator that is used to reverse the logical state of its operand. If the operand is true, the NOT operator will make it false, and if the operand is false, the NOT operator will make it true. It essentially negates the truth value of a given expression.

Binary Operators

Binary operators are operators that operate on two operands . They perform operations on two values, and the result is a single value. Binary operators are used in various mathematical and logical operations. Here are some common binary operators in C:

The assignment operator is the single equals sign (=).

The assignment operator copies the value from its right hand side to the variable on its left hand side. The assignment also acts as an expression which returns the newly assigned value. Some programmers will use that feature to write things like the following.

Other Assignment Operators (>>=, <<=, &=, |= and ^=)

In addition to the plain = operator, C includes many shorthand operators which represents variations on the basic =. For example “+=” adds the right hand side to the left hand side. x = x + 10; can be reduced to x += 10;. This is most useful if x is a long expression such as the following, and in some cases it may run a little faster.

Here’s the list of assignment shorthand operators…

C includes the usual binary and unary arithmetic operators. These are used to perform basic arithmetic operations such as addition (+), subtraction (-), multiplication (*), division (/), and remainder after division (%) modulo division .

Personally, I just use parenthesis liberally to avoid any bugs due to a misunderstanding of precedence. The operators are sensitive to the type of the operands. So division (/) with two integer arguments will do integer division. If either argument is a float, it does floating point division. So (6/4) evaluates to 1 while (6/4.0) evaluates to 1.5 — the 6 is promoted to 6.0 before the division.

These operate on integer or floating point values and return a 0 or 1 boolean value to show the comparisons between two operands.

An absolutely classic pitfall is to write assignment (=) when you mean comparison (==). This would not be such a problem, except the incorrect assignment version compiles fine because the compiler assumes you mean to use the value returned by the assignment. This is rarely what you want

This does not test if x is 3. This sets x to the value 3, and then returns the 3 to the if for testing. 3 is not 0, so it counts as “true” every time. This is probably the single most common error made by beginning C programmers.

The problem is that the compiler is no help — it thinks both forms are fine, so the only defense is extreme vigilance when coding.

In Logical operators in C, the value 0 is false, anything else is true. The operators evaluate left to right and stop as soon as the truth or falsity of the expression can be deduced. (Such operators are called “short circuiting”) In ANSI C, these are furthermore guaranteed to use 1 to represent true, and not just some random non-zero bit pattern.

C includes operators to manipulate memory at the bit level. This is useful for writing low level hardware or operating system code where the ordinary abstractions of numbers, characters, pointers, etc… are insufficient — an increasingly rare need. Bit manipulation code tends to be less “portable”. Code is “portable” if with no programmer intervention it compiles and runs correctly on different types of computers. The bit-wise operations are typically used with unsigned types. In particular, the shift operations are guaranteed to shift 0 bits into the newly vacated positions when used on unsigned values.

Do not confuse the Bit-wise operators with the logical operators. The bit-wise connectives are one character wide (&, |) while the Boolean connectives are two characters wide (&&, ||). The bit-wise operators have higher precedence than the Boolean operators. The compiler will never help you out with a type error if you use & when you meant &&. As far as the type checker is concerned, they are identical– they both take and produce integers since there is no distinct Boolean type.

Similarly the bitwise AND operator ( & ) and the address-of operator ( & ) serve different purposes in C.

Bitwise AND Operator ( & ) is used for performing bitwise AND operation on individual bits of integers.

Address-of Operator ( & ) is used to obtain the memory address of a variable.

Ternary Operators

In C, the ternary operator, often referred to as the conditional operator, is a shorthand way of expressing an if-else statement. It is the only ternary operator in C and has the following syntax:

The conditional operator (also known as the ternary operator ) is a shorthand way of writing an if statement. It allows you to conditionally execute an expression based on the value of a condition. The syntax of the ternary operator is as follows:

The comma operator , in C is used to separate expressions. It evaluates each expression from left to right and returns the value of the rightmost expression. It is often used in places where multiple expressions are syntactically allowed but only one is expected.

For example in the following example, the expressions a++ and b++ are evaluated first and then the expression a + b is evaluated, and the result is assigned to the variable c .

The following diagram shows a list of operators used in C Programming.

Infographic - Operators in C Programming

If you want to see these operators in action, look at the following C Programs:

  • Print Fibonacci series in C
  • Generating Random Number in C/C++
  • Implementation of Base64 Encoding and Decoding in C
  • Kruskal’s Algorithm Implementation in C
  • Porter’s Algorithm in C

About The Author

M. Saqib

Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.

Related Posts

256-Color VGA Programming in C

  • 256-Color VGA Programming in C

Updated Feb 11, 2024

Graphics in C Language

  • Graphics in C Language

Updated Feb 21, 2024

Structure in C Programming

  • Structure in C Programming

A Complete Guide to using Double Pointer in C: Pointer-to-Pointer

  • A Complete Guide to using Double Pointer in C: Pointer-to-Pointer
  • C++23: Exploring the New Features
  • Control Flow in C Programming – The for and while Loop
  • Pure Virtual Functions in C++
  • Understanding the Basics of C++ Programming
  • What are the Best C++ Compilers to use in 2024?
  • Difference between char[] and char* in C? Character Array and Pointer
  • What are #ifndef and #define Directives?
  • C++ Standard Template Library – List
  • C++ Vectors – std::vector – Containers Library
  • Ternary Operator with examples in C
  • File Handling in C++
  • Ternary Operator with examples in C++
  • Polymorphism in C++
  • The C++ Modulus Operator [mod or % operator]
  • Introduction to C++ – Lecture Notes
  • An Introduction to C++
  • Concurrency in C++ – A Course offered by University of Waterloo
  • Union in C Programming
  • Basic Data Types in C Programming
  • Advanced C++ Inheritance Techniques for Effective Object-Oriented Programming
  • Inheritance in C++
  • C++ Memory Management
  • Transitioning from C to C++: A Quick Guide for Novice Programmers
  • Understanding the Basics of Encapsulation in C++
  • Functions in C++ Programming
  • Learn File Handling Concepts in C Programming
  • Virtual Functions in C++
  • Multiple Inheritance in C++
  • An overview of Generic Containers in C++
  • Compounded Types in C++
  • Pointers in C++
  • Advanced Concepts and Patterns in Encapsulation
  • Constructors in C++
  • Working with Pointers in C
  • Destructors in C++
  • Introduction to Classes in C++
  • C++ and Object Orientation
  • Generic Algorithms – Unlocking the Power of C++ STL Algorithms
  • Understanding C++ Templates: A Simplified Guide
  • Strings in C++: A Complete Guide for Novice Programmers
  • The Standard C++ Library
  • A Guide to Advanced Exception Handling in C++ Programming
  • Operator Overloading in C++
  • Exception Handling in C++
  • Conditional Statements – Decision Statements – if, else
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • Compound Statements in C++
  • Rethrowing an Exception in C++
  • Variable Shadowing in C++
  • Condition Variables in C++ Multithreading
  • C++23 <print> Header
  • Literals In C++
  • How to Define Constants in C++?
  • C++ Variable Templates
  • Introduction to GUI Programming in C++
  • Concurrency in C++
  • Hybrid Inheritance In C++
  • Dereference Pointer in C
  • shared_ptr in C++
  • Nested Inline Namespaces In C++20
  • C++20 std::basic_syncbuf
  • std::shared_mutex in C++
  • Partial Template Specialization in C++
  • Pass By Reference In C
  • Address Operator & in C

Assignment Operators In C++

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

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

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

Compound Assignment Operators

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

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

Lets see each of them in detail.

1. Addition Assignment Operator (+=)

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

This above expression is equivalent to the expression:

2. Subtraction Assignment Operator (-=)

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

3. Multiplication Assignment Operator (*=)

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

4. Division Assignment Operator (/=)

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

5. Modulus Assignment Operator (%=)

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

6. Bitwise AND Assignment Operator (&=)

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

7. Bitwise OR Assignment Operator (|=)

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

8. Bitwise XOR Assignment Operator (^=)

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

9. Left Shift Assignment Operator (<<=)

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

10. Right Shift Assignment Operator (>>=)

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

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

Please Login to comment...

Similar reads.

  • Geeks Premier League 2023
  • Geeks Premier League
  • 10 Best Slack Integrations to Enhance Your Team's Productivity
  • 10 Best Zendesk Alternatives and Competitors
  • 10 Best Trello Power-Ups for Maximizing Project Management
  • Google Rolls Out Gemini In Android Studio For Coding Assistance
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Pointer Expressions in C with Examples

    c assignment operator pointer

  2. Pointer Expressions in C with Examples

    c assignment operator pointer

  3. Pointer Expressions in C with Examples

    c assignment operator pointer

  4. C Pointers

    c assignment operator pointer

  5. Pointer Expressions in C with Examples

    c assignment operator pointer

  6. Pointer Expressions in C with Examples

    c assignment operator pointer

VIDEO

  1. Indirection (*) and Address of (&) operator

  2. Augmented assignment operators in C

  3. Assignment Operator in C Programming

  4. Assignment Operator in C Programming

  5. JS Coding Assignment-2

  6. What are Pointers? How to Use Them? and How they can Improve your C++ Programming Skills

COMMENTS

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

  2. c++

    4. Correct me if I'm wrong: I understand that when having a class with members that are pointers, a copy of a class object will result in that the pointers representing the same memory address. This can result in changes done to one class object to affect all copies of this object. A solution to this can be to overload the = operator.

  3. Assignment Operators in C

    Different types of assignment operators are shown below: 1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: 2. "+=": This operator is combination of '+' and '=' operators.

  4. C Pointers (With Examples)

    Explanation of the program. int* pc, c; Here, a pointer pc and a normal variable c, both of type int, is created. Since pc and c are not initialized at initially, pointer pc points to either no address or a random address. And, variable c has an address but contains random garbage value.; c = 22; This assigns 22 to the variable c.That is, 22 is stored in the memory location of variable c.

  5. How C-Pointers Works: A Step-by-Step Beginner's Tutorial

    To declare and initialize a pointer to a pointer, you need to add an extra asterisk (*) compared to a regular pointer. Let's go through an example: int x = 10; int *ptr1 = &x; // Pointer to an integer int **ptr2 = &ptr1; // Pointer to a pointer to an integer. In this example, ptr2 is a pointer to a pointer.

  6. C Pointers Tutorial: Chapter 1

    The lvalue is the value permitted on the left side of the assignment operator '=' (i.e. the address where the result of evaluation of the right side ends up). The rvalue is that which is on the right side of the assignment statment, the '2' above. ... In C when we define a pointer variable we do so by preceding its name with an asterisk. In C ...

  7. Pointers

    This is a standard assignment operation, as already done many times in earlier chapters. The main difference between the second and third statements is the appearance of the address-of operator (&). The variable that stores the address of another variable (like foo in the previous example) is what in C++ is called a pointer. Pointers are a very ...

  8. Assignment Operators in C

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

  9. C Pointers

    The use of pointers in C can be divided into three steps: Pointer Declaration. Pointer Initialization. Pointer Dereferencing. 1. Pointer Declaration. In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name. Example.

  10. 12.7

    In the above example, we define pointer ptr, initialize it with the address of x, and dereference the pointer to print the value being pointed to (5). We then use the assignment operator to change the address that ptr is holding to the address of y. We then dereference the pointer again to print the value being pointed to (which is now 6).

  11. C++ pointer assignment

    Now we have two variables x and y: int *p = &x; int *q = &y; There are declared another two variables, pointer p which points to variable x and contains its address and pointer q which points to variable y and contains its address: x = 35; y = 46; Here you assign values to the variables, this is clear: p = q;

  12. 21.12

    21.12 — Overloading the assignment operator. Alex November 27, 2023. The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports "Move assignment". We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

  13. c++

    The assignment operator performs a member-wise assignment of every data member of the class for which it is defined. That means if there is some pointer p in class X, the assignment operator will simply assign it to the pointer from that other object. For example: X& X::operator=(const X& rhs) { // default-assignment operator. this->p = rhs.p;

  14. Operators in C Programming

    Pointer Operators (*, & and ->) In C, pointer operators are operators that are used in conjunction with pointers. There are several pointer operators in C, including: Address-of operator (&): Returns the memory address of a variable.When used with a variable, the & operator returns the address of the variable in memory.; Dereference operator (*): Accesses the value stored at a memory address.

  15. Arrow operator -> in C/C++ with Examples

    An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below. Syntax: (pointer_name)->(variable_name) Operation: The -> operator in C or C++ gives the value ...

  16. pointers

    Sep 23, 2013 at 21:41. Rule of Five: When C++11 is used (as is becoming more and more prevalent nowadays), the rule of three is replaced by the "Rule of Five". That means that in addition to a copy constructor, destructor, (copy) assignment operator, now also a move constructor and move assignment operator should be defined. - Piotr99.

  17. [committed] c++: Fix ICE with weird copy assignment operator [PR114572]

    > > While ctors/dtors don't return anything (undeclared void or this pointer > on arm) and copy assignment operators normally return a reference to *this, > it isn't invalid to return uselessly some class object which might need > destructing, but the OpenMP clause handling code wasn't expecting that. > > The following patch fixes that.

  18. Assignment Operators In C++

    In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way. Syntax. variable += value; This above expression is equivalent to the expression: variable = variable + value; Example.

  19. C++ Assignment operator for class that contains a unique pointer member

    If GraphStructure is a class or struct without any virtual member functions, this is easy to do. We can write a function to duplicate the data inside a unique_ptr to create a new GraphStructure: std::unique_ptr<GraphStructure> duplicate(std::unique_ptr<GraphStructure> const& ptr) {. return std::make_unique<GraphStructure>(*ptr);