Library homepage

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

selected template will load here

This action is not available.

Engineering LibreTexts

4.6: Assignment Operator

  • Last updated
  • Save as PDF
  • Page ID 29038

  • Patrick McClanahan
  • San Joaquin Delta College

Assignment Operator

The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol. But bite your tongue, when you see the = symbol you need to start thinking: assignment. The assignment operator has two operands. The one to the left of the operator is usually an identifier name for a variable. The one to the right of the operator is a value.

The value 21 is moved to the memory location for the variable named: age. Another way to say it: age is assigned the value 21.

The item to the right of the assignment operator is an expression. The expression will be evaluated and the answer is 14. The value 14 would assigned to the variable named: total_cousins.

The expression to the right of the assignment operator contains some identifier names. The program would fetch the values stored in those variables; add them together and get a value of 44; then assign the 44 to the total_students variable.

As we have seen, assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below:

  • “=” : This is the simplest assignment operator, which was discussed above. This operator is used to assign the value on the right to the variable on the left. For example: a = 10; b = 20; ch = 'y';

If initially the value 5 is stored in the variable a,  then:  (a += 6) is equal to 11.  (the same as: a = a + 6)

If initially value 8 is stored in the variable a, then (a -= 6) is equal to  2. (the same as a = a - 6)

If initially value 5 is stored in the variable a,, then (a *= 6) is equal to 30. (the same as a = a * 6)

If initially value 6 is stored in the variable a, then (a /= 2) is equal to 3. (the same as a = a / 2)

Below example illustrates the various Assignment Operators:

Definitions

 Adapted from:  "Assignment Operator"  by  Kenneth Leroy Busbee , (Download for free at http://cnx.org/contents/[email protected] ) is licensed under  CC BY 4.0

Home » Learn C Programming from Scratch » C Assignment Operators

C Assignment Operators

Summary : in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.

Introduction to the C assignment operators

An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:

After the assignmment, the counter variable holds the number 1.

The following example adds 1 to the counter and assign the result to the counter:

The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.

Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

The following example uses a compound-assignment operator (+=):

The expression:

is equivalent to the following expression:

The following table illustrates the compound-assignment operators in C:

  • A simple assignment operator assigns the value of the left operand to the right operand.
  • A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

This browser is no longer supported.

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

Assignment operators

  • 8 contributors

expression assignment-operator expression

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

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

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

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

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

Assignment operators table

Operator keywords.

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

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

Simple assignment

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

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

Assignment to objects of class type ( struct , union , and class types) is performed by a function named operator= . The default behavior of this operator function is to perform a member-wise copy assignment of the object's non-static data members and direct base classes; however, this behavior can be modified using overloaded operators. For more information, see Operator overloading . Class types can also have copy assignment and move assignment operators. For more information, see Copy constructors and copy assignment operators and Move constructors and move assignment operators .

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

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

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

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

the assignment statement

can have one of the following effects:

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

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

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

Compound assignment

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

an arithmetic type

a pointer, if op is + or -

a type for which there exists a matching operator *op*= overload for the type of e1

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

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

Result of built-in assignment operators

The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

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

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

Was this page helpful?

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

Submit and view feedback for

Additional resources

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - While loop
  • C - Functions
  • C - Main Functions
  • C - Return Statement
  • 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 - Recursion
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Assignment Operators in C

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

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

Simple assignment operator (=)

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

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

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

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

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

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

Augmented assignment operators

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

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

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

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

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

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Assignment operator in c.

' src=

Last Updated on June 23, 2023 by Prepbytes

c what does assignment return

This type of operator is employed for transforming and assigning values to variables within an operation. In an assignment operation, the right side represents a value, while the left side corresponds to a variable. It is essential that the value on the right side has the same data type as the variable on the left side. If this requirement is not fulfilled, the compiler will issue an error.

What is Assignment Operator in C language?

In C, the assignment operator serves the purpose of assigning a value to a variable. It is denoted by the equals sign (=) and plays a vital role in storing data within variables for further utilization in code. When using the assignment operator, the value present on the right-hand side is assigned to the variable on the left-hand side. This fundamental operation allows developers to store and manipulate data effectively throughout their programs.

Example of Assignment Operator in C

For example, consider the following line of code:

Types of Assignment Operators in C

Here is a list of the assignment operators that you can find in the C language:

Simple assignment operator (=): This is the basic assignment operator, which assigns the value on the right-hand side to the variable on the left-hand side.

Addition assignment operator (+=): This operator adds the value on the right-hand side to the variable on the left-hand side and assigns the result back to the variable.

x += 3; // Equivalent to x = x + 3; (adds 3 to the current value of "x" and assigns the result back to "x")

Subtraction assignment operator (-=): This operator subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result back to the variable.

x -= 4; // Equivalent to x = x – 4; (subtracts 4 from the current value of "x" and assigns the result back to "x")

* Multiplication assignment operator ( =):** This operator multiplies the value on the right-hand side with the variable on the left-hand side and assigns the result back to the variable.

x = 2; // Equivalent to x = x 2; (multiplies the current value of "x" by 2 and assigns the result back to "x")

Division assignment operator (/=): This operator divides the variable on the left-hand side by the value on the right-hand side and assigns the result back to the variable.

x /= 2; // Equivalent to x = x / 2; (divides the current value of "x" by 2 and assigns the result back to "x")

Bitwise AND assignment (&=): The bitwise AND assignment operator "&=" performs a bitwise AND operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x &= 3; // Binary: 0011 // After bitwise AND assignment: x = 1 (Binary: 0001)

Bitwise OR assignment (|=): The bitwise OR assignment operator "|=" performs a bitwise OR operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x |= 3; // Binary: 0011 // After bitwise OR assignment: x = 7 (Binary: 0111)

Bitwise XOR assignment (^=): The bitwise XOR assignment operator "^=" performs a bitwise XOR operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x ^= 3; // Binary: 0011 // After bitwise XOR assignment: x = 6 (Binary: 0110)

Left shift assignment (<<=): The left shift assignment operator "<<=" shifts the bits of the value on the left-hand side to the left by the number of positions specified by the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x <<= 2; // Binary: 010100 (Shifted left by 2 positions) // After left shift assignment: x = 20 (Binary: 10100)

Right shift assignment (>>=): The right shift assignment operator ">>=" shifts the bits of the value on the left-hand side to the right by the number of positions specified by the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x >>= 2; // Binary: 101 (Shifted right by 2 positions) // After right shift assignment: x = 5 (Binary: 101)

Conclusion The assignment operator in C, denoted by the equals sign (=), is used to assign a value to a variable. It is a fundamental operation that allows programmers to store data in variables for further use in their code. In addition to the simple assignment operator, C provides compound assignment operators that combine arithmetic or bitwise operations with assignment, allowing for concise and efficient code.

FAQs related to Assignment Operator in C

Q1. Can I assign a value of one data type to a variable of another data type? In most cases, assigning a value of one data type to a variable of another data type will result in a warning or error from the compiler. It is generally recommended to assign values of compatible data types to variables.

Q2. What is the difference between the assignment operator (=) and the comparison operator (==)? The assignment operator (=) is used to assign a value to a variable, while the comparison operator (==) is used to check if two values are equal. It is important not to confuse these two operators.

Q3. Can I use multiple assignment operators in a single statement? No, it is not possible to use multiple assignment operators in a single statement. Each assignment operator should be used separately for assigning values to different variables.

Q4. Are there any limitations on the right-hand side value of the assignment operator? The right-hand side value of the assignment operator should be compatible with the data type of the left-hand side variable. If the data types are not compatible, it may lead to unexpected behavior or compiler errors.

Q5. Can I assign the result of an expression to a variable using the assignment operator? Yes, it is possible to assign the result of an expression to a variable using the assignment operator. For example, x = y + z; assigns the sum of y and z to the variable x.

Q6. What happens if I assign a value to an uninitialized variable? Assigning a value to an uninitialized variable will initialize it with the assigned value. However, it is considered good practice to explicitly initialize variables before using them to avoid potential bugs or unintended behavior.

Leave a Reply Cancel reply

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

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

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Null character in c, ackermann function in c, median of two sorted arrays of different size in c, number is palindrome or not in c, implementation of queue using linked list in c, c program to replace a substring in a string.

Learn C practically and Get Certified .

Popular Tutorials

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

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

C Flow Control

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

C Functions

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

C Programming Strings

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

Structure And Union

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

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

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

Bitwise Operators in C Programming

C Precedence And Associativity Of Operators

  • Compute Quotient and Remainder
  • Find the Size of int, float, double and char

C if...else Statement

  • Demonstrate the Working of Keyword long

C Programming Operators

An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.

C has a wide range of operators to perform various operations.

C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).

Example 1: Arithmetic Operators

The operators + , - and * computes addition, subtraction, and multiplication respectively as you might have expected.

In normal calculation, 9/4 = 2.25 . However, the output is 2 in the program.

It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25 .

The modulo operator % computes the remainder. When a=9 is divided by b=4 , the remainder is 1 . The % operator can only be used with integers.

Suppose a = 5.0 , b = 2.0 , c = 5 and d = 2 . Then in C programming,

C Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.

Example 2: Increment and Decrement Operators

Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes like a++ and a-- . Visit this page to learn more about how increment and decrement operators work when used as postfix .

C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment operator is =

Example 3: Assignment Operators

C relational operators.

A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops .

Example 4: Relational Operators

C logical operators.

An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming .

Example 5: Logical Operators

Explanation of logical operator program

  • (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
  • (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
  • (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
  • (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
  • !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
  • !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Visit bitwise operator in C to learn more.

Other Operators

Comma operator.

Comma operators are used to link related expressions together. For example:

The sizeof operator

The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).

Example 6: sizeof Operator

Other operators such as ternary operator ?: , reference operator & , dereference operator * and member selection operator  ->  will be discussed in later tutorials.

Table of Contents

  • Arithmetic Operators
  • Increment and Decrement Operators
  • Assignment Operators
  • Relational Operators
  • Logical Operators
  • sizeof Operator

Video: Arithmetic Operators in C

Sorry about that.

Related Tutorials

Next: Unions , Previous: Overlaying Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

cppreference.com

Return statement.

Terminates the current function and returns the specified value (if any) to the caller.

[ edit ] Syntax

[ edit ] explanation, [ edit ] notes.

If control reaches the end of

  • a function with the return type (possibly cv-qualified) void ,
  • a constructor,
  • a destructor, or
  • a function-try-block for a function with the return type (possibly cv-qualified) void

without encountering a return statement, return ; is executed.

If control reaches the end of the main function , return 0 ; is executed.

Flowing off the end of a value-returning function, except main and specific coroutines (since C++20) , without a return statement is undefined behavior.

In a function returning (possibly cv-qualified) void , the return statement with expression can be used, if the expression type is (possibly cv-qualified) void .

Returning by value may involve construction and copy/move of a temporary object, unless copy elision is used. Specifically, the conditions for copy/move are as follows:

and that variable is declared

  • in the body or
  • as a parameter
  • then overload resolution is performed as usual, with expression considered as an lvalue (so it may select the copy constructor ).

If the expression is move-eligible, it is treated as an xvalue (thus overload resolution may select the move constructor ).

[ edit ] Keywords

return , co_return

[ edit ] Example

[ edit ] defect reports.

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

[ edit ] See also

  • copy elision
  • 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 5 March 2024, at 15:28.
  • This page has been accessed 405,915 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

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

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions
  • Solve Coding Problems
  • C if else if ladder
  • Break Statement in C
  • Continue Statement in C
  • C Programming Language Standard
  • Global Variables in C
  • Basic Code Optimizations in C
  • Tokens in C
  • printf in C
  • while loop in C
  • Escape Sequence in C
  • Structure of the C Program
  • Newline in C
  • Data type of case labels of switch statement in C++?
  • Jump Statements in C
  • Using Range in switch Case in C
  • C Program to print environment variables
  • Comment in header file name?
  • main Function in C

Return Statement in C

Pre-requisite: Functions in C

C return statement ends the execution of a function and returns the control to the function from where it was called . The return statement may or may not return a value depending upon the return type of the function. For example, int returns an integer value, void returns nothing, etc.

In C, we can only return a single value from the function using the return statement and we have to declare the data_type of the return value in the function definition/declaration.

working of return statement

Working of Return Statement

There are various ways to use return statements. A few are mentioned below:

1. Methods not returning a value

 In C, one cannot skip the return statement when the return type of the function is non-void type. The return statement can be skipped only for void types.

A. Not using a return statement in void return type function:  

While using the void function, it is not necessary to use return as the void itself means nothing(an empty value).

Example:  

B. Using the return statement in the void return type function

As void means empty, we don’t need to return anything, but we can use the return statement inside void functions as shown below. Although, we still cannot return any value.

This syntax is used in function as a jump statement in order to break the flow of the function and jump out of it. One can think of it as an alternative to “ break statement ” to use in functions. 

But if the return statement tries to return a value in a void return type function, that will lead to errors. 

Incorrect Syntax:

2. Methods returning a value

For functions that define a non-void return type in the definition and declaration, the return statement must be immediately followed by the return value of that specified return type.

  Syntax:

Note : A function can only return a single value using return statement. To return multiple values, we use pointers or structures. Know more about refer to the article – How to return multiple values from a function in C or C++?.

Please Login to comment...

  • Node.js 21 is here: What’s new
  • Zoom: World’s Most Innovative Companies of 2024
  • 10 Best Skillshare Alternatives in 2024
  • 10 Best Task Management Apps for Android in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

CS 2110: Object-Oriented Programming and Data Structures

Assignment 4: formula evaluation.

Programming languages give us as programmers the ability to evaluate mathematical expressions like a calculator, including expressions that involve variables. The language’s compiler translates the formula into instructions that a computer’s CPU can execute. But what if we want our program’s users to be able to type in their own expressions at runtime and have them be evaluated? Their formula will be user input (a String ), not source code, so we’ll need our program to evaluate it step-by-step with the help of appropriate data structures.

As an application, let’s once again consider spreadsheets. Some cells contain plain text or numbers, but other cells may specify a formula that should be used to compute its value, taking as input the values of other cells. For example, in Microsoft Excel, the formula =A1+B1 means that the cell’s value should be the sum of the values in row 1, columns A & B (see figure).

Screenshot of Microsoft Excel

In this assignment, you will write an application that evaluates postfix formulas in spreadsheets saved in CSV format. Along the way you will develop an interactive calculator to help build intuition for the data structures involved. This project involves a lot of Java classes; some of them will be given to you (in which case you must study their specifications as a client ), while others you will develop from scratch. As usual, you will write JUnit test cases for all of your code, annotated with human-readable assertions of specifications.

Learning Objectives

  • Leverage subtype polymorphism to represent expression trees containing multiple kinds of nodes.
  • Process tree data structures recursively.
  • Report and respond to failed operations using exceptions.
  • Write tests (using lambdas) that expect exceptions to be thrown.
  • Use classes from a third-party library.

Recommended schedule

Start early. This is a big assignment! Office hours and consulting hours are significantly quieter shortly after an assignment is released than closer to the deadline. We recommend spreading your work over at least 5 days. Here is an example of what that schedule could be:

  • Day 1: Read this handout and open the project in IntelliJ. Confirm that the test suites compile and run. Part I—Test and implement eval() and opCount() for all Expression classes. Write “stubs” for all other Expression methods so that your code compiles and your tests can run.
  • Day 2: Part I continued—Test and implement infixString() and postfixString() for all Expression classes. Then test and implement equals() (which will come in handy for future tests).
  • Day 3: Part II—Test and implement RpnParser , then perform further testing by using RpnCalc to interact with your expression trees.
  • Day 4: Part III—Return to your Expression classes and test and implement dependencies() and optimize() . Use RpnCalc to see this functionality in action.
  • Day 5: Part IV—Implement CsvEvaluator . Test it both with the provided unit tests and with the provided CSV files. Try creating and evaluating a few spreadsheets of your own.

Note that this schedule does not include the challenge extensions. If you plan on tackling these, be sure to leave an extra couple of days at the end of your schedule.

Collaboration policy

On this assignment you may work together with one partner. Having a partner is not needed to complete the assignment: it is definitely do-able by one person. Nonetheless, working with another person is useful because it gives you a chance to bounce ideas off each other and to get their help with fixing faults in your shared code. If you do intend to work with a partner, you must review the syllabus policies pertaining to partners under “programming assignments” and “academic integrity.”

Partnerships must be declared by forming a group on CMSX before starting work. The deadline to form a CMS partnership is Friday, March 22 . After that, CMSX will not allow you to form new partnerships on your own. You may still email your section TA (CCing your partner) to form a group late, but a 5 point penalty will be applied. This is to make sure you are working with your partner on the entire assignment, as required by the syllabus, rather than joining forces part way through.

As before, you may talk with others besides your partner to discuss Java syntax, debugging tips, or navigating the IntelliJ IDE, but you should refrain from discussing algorithms that might be used to solve the problems, and you must never show your in-progress or completed code to another student who is not your partner. Consulting hours are the best way to get individualized assistance at the source code level.

Frequently asked questions

Note: This assignment includes some “challenge extensions” that are worth very few points but will provide a lot of additional practice for students who choose to tackle them. Do not feel discouraged if you don’t have time to try these challenges—you can still earn an ‘A’ grade without attempting them at all. If you do attempt them, course staff will only be able to provide limited debugging assistance.

If needed, there will be a pinned post on Ed where we will collect any clarifications for this assignment. Please review it before asking a new question in case your concern has already been addressed. You should also review the FAQ before submitting to see whether there are any new ideas that might help you improve your solution.

Remember that the student handbook outlines requirements that apply to all assignments in this course. Please ensure that your submission complies with these to avoid deductions during grading.

Assignment overview

For this assignment you will be creating three Java classes from scratch (representing polymorphic expression tree nodes) and completing two applications: an interactive calculator and a spreadsheet formula evaluator .

Make sure to open the “a4” folder as a project in IntelliJ following the procedure from previous assignments (this is extra important for this assignment, as it depends on a third-party library in the “lib” folder). If IntelliJ complains about standard Java classes, try “File | Repair IDE” and advance it through “step 3”. Here is a brief tour of what you’ll find inside your project:

Whew! Your programs are getting bigger! Fortunately, you only need to worry about submitting 4 of these files (plus 3 new ones you will create).

Note that achieving reasonable coverage of the expression classes requires a lot of test cases. But each one only needs a couple lines of code, and we have provided English descriptions of the cases that you need.

Part I: Expression nodes

Expression trees.

As discussed in lecture 14, a tree is a natural data structure for representing mathematical expressions, since operands and function arguments are themselves subexpressions. Consider the expression $2 \cdot (y - 1) + 3$. The operands to the multiplication operator are the constant $2$ and the subexpression $(y - 1)$. And the whole subexpression $2 \cdot (y - 1)$ serves as the first operand to the addition operator. These hierarchical relationships form a tree as shown in the figure, which each node containing either a constant, a variable, or an operator.

Expressions are evaluated recursively: an operator node recursively evaluates its left operand, then its right operand, and then combines those returned values to produce its result. An operator always has two children (its left and right operands), but in this assignment we will also support function nodes, like sin() and cos() , that have a single child (their argument subexpression).

To review mathematical expressions and their representation as trees, see the following textbook sections:

  • Segment 5.5 (Using a Stack to Process Algebraic Expressions), focusing on 5.17–5.18
  • Chapter 24, 24.22–24.24 (Expression Trees)

Reverse Polish notation (RPN)

We are used to writing mathematical expressions in “infix” notation, like 2*(y - 1) + 3 . However, this notation requires knowing the precedence of each operator (e.g., multiplication/division before addition/subtraction), and parentheses are often required to achieve the desired order of operations. Parsing such expressions in software is, consequently, a little tricky. But there is another way to write expressions that never requires parentheses, corresponding to a postorder traversal of the corresponding expression tree. This is called “postfix notation,” a.k.a. “reverse Polish notation” (RPN).

As an example, the previous expression would be written in RPN as 2 y 1 - * 3 + . For this assignment, all formulas typed into your calculator or saved in spreadsheets will be in reverse Polish notation.

Here are some correspondences between our infix and RPN notations:

Note that, to eliminate any possibility of ambiguity, every binary operation is enclosed in parentheses in our infix notation.

Our Expression interface

Our expression trees will be composed of polymorphic nodes implementing the Expression interface. This means that each node could have a different class, each one specializing Expression in a particular way (i.e., constant numbers vs. binary operators). For example, the expression $1 - 2 \sin^2(y / 2)$ would be represented by the following tree, where “C” indicates a Constant node, “V” indicates a Variable node, “A” indicates an Application node, and “O” indicates an Operation node:

Here is a class diagram showing the methods required by Expression and the fields of the concrete classes that you’ll be writing:

Expressions can be evaluated, they can count how many operations are required to evaluate them, and they can write themselves in infix or postfix notation. Read the specifications in “Expression.java” for the specifics.

The Constant class has been written for you. It represents a single number, stored in its value field.

Define public classes Variable , Application , and Operation implementing the Expression interface in new corresponding “.java” files. Start by creating “stubs” for each of the required methods (IntelliJ can do this for you; see below). Declare the fields that will represent each class’s state according to the class diagram above, then define constructors to initialize those fields. (You may order your constructor parameters however you like, so long as their interpretation is clear from their specifications. There is a small advantage to following the order of the fields in the diagram above, as that will match some test templates we provide to you.)

You can choose whether to implement all the methods in one class before moving on to the next one, or whether to implement one method at a time across all of the classes. We recommend the latter, as it will enable you to test each operation on arbitrary expressions as you go.

Here is a brief overview of these three classes. These descriptions should be enough for you to write specialized specifications for eval() , opCount() , infixString() , postfixString() , and equals() in each class. The remaining operations will be discussed later.

Variable nodes

These represent a named variable (like $y$) in an expression; their state is simply the variable’s name. Variables are useful because they allow us to write down an expression without yet knowing the values of all of the terms. For example, in our spreadsheet formulas, variables with names like “B1” will refer to values in other cells of the spreadsheet. To evaluate expressions containing variables, a client must pass in a VarTable containing the values of those variables.

Like constants, variable nodes are leaf nodes and have no children. When evaluated, they return the value of their variable (if it exists in the VarTable ), or else they throw an UnboundVariableException . We do not consider this lookup to be an “operation” as counted by opCount() . When a variable is written as a string, a variable is simply represented by its name, regardless of notation (infix vs. postfix).

Since variable nodes are leaves, two of them are equal if they represent the same variable name.

Application nodes

These represent the application of a function to an argument ; the argument can be any non-empty subexpression. For example, the expression $\sin(y / 2)$ expresses the application of the $\sin()$ function to the subexpression $y / 2$. The argument is stored as a single child Expression node. The function to call is an instance of our UnaryFunction class, which can be evaluated on a numeric argument by calling its apply() method. UnaryFunction can also report its name so we know how to identify the function in a string.

To evaluate an Application node, it should evaluate its argument child, then apply its function to that value and return the result. Calling its function counts as one “operation”. In infix notation, an Application is represented by the name of its function, followed by the infix representation of its argument, enclosed in parentheses. For example, the expression above would be written as "sin((y / 2))" (note the double parentheses—one pair for the function application, and one pair for the Operation argument, to be discussed next). In postfix notation, an Application is represented by its argument’s postfix string, followed by the function name with a "()" suffix (this is to distinguish functions from variables). E.g., "y 2 / sin()" .

Two Application nodes are equal if their functions and arguments are equal.

Operation nodes

These represent the binary operators common in arithmetic: addition ( + ), subtraction ( - ), multiplication ( * ), division ( / ), and exponentiation ( ^ ). Their operands are stored as two child Expression nodes, distinguishing between left and right (since subtraction, division, and exponentiation are not commutative). The operator is an instance of our Operator class, which can be evaluated on numeric operands by calling its operate() method. Operator can also report its symbol so we know how to identify it in a string.

To evaluate an Operation node, it should evaluate both of its operand children, then combine those value with its operator and return the result. This counts as one “operation”. In infix notation, an Operation is always enclosed in parentheses, and its operands are separated from its operator symbol by spaces. What we would write mathematically as $(2 y + 1)^3$ should be expressed as the string "(((2 * y) + 1) ^ 3)" . To express an Operation in postfix notation, simply perform a postorder traversal, as discussed in lecture for binary trees. The same expression in postfix notation would be "2 y * 1 + 3 ^" .

Two Operation nodes are equal if their operator and operands are equal.

Note: you should not need to do any dynamic type queries (i.e., instanceof , getClass() , casting) when implementing the behavior of the various expression nodes (other than in equals() , where our usual template is fine). Nor should you need to write any loops. Rely on recursion and subtype polymorphism and trust your child nodes to do the right thing.

Testing expressions

“ExpressionTest.java” declares nearly 50 unit tests for the various Expression classes. About half of the tests have been implemented for you, while you are responsible for implementing the remaining ones. As usual, we strongly recommend implementing (or uncommenting) the tests related to the behavior you are about to implement. Writing (or reading) the test case will clarify the function’s specification for you, and seeing the case change from “fail” to “pass” provides a reward when your method implementation is on the right track. And if a test doesn’t turn green, you know exactly which code must be at fault.

Each case is annotated with a @DisplayName() that describes the behavior being tested. The description gives the context, identifies the operation being performed, and specifies the expected result. It is hopefully clear how each case relates to the specifications of a class’s methods; occasionally these descriptions may even help clarify a dense specification.

For each case that says fail(); // TODO , you are responsible for replacing this stub with a test implementation that meets the criteria described by the @DisplayName() . You are encouraged to copy-paste portions of other tests to speed up this process as long as the result is consistent with the test description.

Some tests have already been implemented but have been commented out. This is because we did not specify the constructor signatures for your Expression classes. You must uncomment each of these cases and adjust the constructor invocations (if necessary) so that the tests run.

Despite the relatively large number of tests in this suite, it probably still does not provide 100% line coverage of your classes (though hopefully it covers at least 90%). Furthermore, it does not come close to testing all possible combinations of node types, operators, functions, and variable names. But writing clear specifications at the interface level, then testing that each component meets those specifications individually, is still critical for avoiding bugs when composing software modules in arbitrary ways like this.

Testing exceptions

Since some of the methods promise to throw an exception under certain conditions, you should include tests that check whether an exception is thrown as specified. The JUnit function assertThrows() is the right tool for the job, but it works a little differently than other JUnit assertions. You must specify the expected exception’s Class object, and you must defer execution of the exception-throwing code using an anonymous function .

Let’s take testEvalUnbound() in VariableExpressionTest as an example. When eval() is called on a Variable expression expr , we expect it to throw an UnboundVariableException if the variable’s name is not in the provided VarTable argument. This behavior is tested using the following code:

We’ll come back to anonymous functions in more detail later in the course, but for now you can use them in this idiomatic way by just putting () -> in front of expressions whose evaluation needs to be deferred.

Part II: Parsing RPN expressions

As you likely concluded from your testing, assembling expression trees from individual nodes is tedious. We need a way to parse a postfix expression string, provided by a user, and return the corresponding expression tree (this is basically the inverse of the postfixString() methods you implemented earlier). This is the job of RpnParser.parse() .

Implementing this parser is the most important part of the assignment. Since we didn’t dictate the order of constructor arguments for your Expression classes, the only way our autograder will be able to create expression nodes is by parsing expression strings using your RpnParser . It will also probably be the longest method you write for this assignment.

Given an expression in RPN, you build the expression tree from the bottom up using the following procedure:

  • Initialize a Stack of expression nodes.
  • If the token is a number or a variable name, push a corresponding leaf node onto the stack.
  • If the token is an operator or a function name, pop the appropriate number of operands/arguments off of the stack, construct a new interior node with the operation and arguments, and push the new node onto the stack.
  • Assuming the expression is valid, there will be one node left on the stack. This is the root of the expression tree.

Playing with an RPN calculator can help build your intuition for this procedure.

In RpnParser.parse() , we start you off with a few key elements: an empty stack of Expression nodes and an iteration over Token s. The tokens are created by splitting the expression string at whitespace, then determining whether each substring is a number, an operator, a function call (ending in "()" ), or a variable name (any other string). Each token will therefore be one of the following subclasses of Token (the Token. prefix just indicates that they were defined as nested classes in the same file):

  • Token.Number
  • Token.Operator (note: this is not the same class as Operator )
  • Token.Function
  • Token.Variable

As described by the TODO, you should query the dynamic type of each token yielded by the iteration (using instanceof ), then take the appropriate action for each kind. If you ever need to pop more expressions off the stack than are available, you should throw IncompleteRpnException ; likewise if, at the end of the procedure, there is not exactly one Expression remaining. Note that each subclass of Token defines some useful behavior, accessible via appropriate casting. For example, a Token.Operator can give you its corresponding Operator object via opValue() . Functions, however, must be looked up from the funcDefs argument provided by the client (this is to support user-defined functions , one of the challenge extensions).

Implement your parser , then test it against the cases in RpnParserTest . Note that this testing is deliberately incomplete. Heed the advice in the comments add additional test cases to ensure that your parser is working as expected. There are plenty of examples of postfix expressions in this handout that you can use.

Part III: Calculator functionality

Once your parser is implemented, you can interact with your expressions using the RpnCalc calculator app. This calculator has already been implemented (except for a few advanced functions left as challenges), so go ahead and run it and type help to see the commands that are available. The calculator remembers the last expression that was entered, so if you do not provide a new expression with each command, it will reuse the old one (the square brackets around [<expr>] in the help message indicate that the argument is optional).

Type eval 2 1 1 0 + + + to evaluate $2 + 1 + 1 + 0$. Type infix to print the expression in infix notation. Type opcount to count the number of operations needed to evaluate it. To exercise variables and functions, try set pi 3.1415926535897932 , then eval pi 2 / sin() .

The file “calc-commands.txt” contains another sequence of calculator commands. To run them all at once, you can pass the filename as a program argument to RpnCalc . However, it will crash when trying to run the deps and optimize commands if you still have stubs in your expression classes. Let’s fix that.

Variable dependencies

If a formula gets very long, it might be handy to know all of the variables it depends on. Since the same variable may appear in multiple subexpressions, a Set of variable names is the appropriate ADT to represent this information (so duplicates are not repeated).

Implement the dependencies() method in all of your Expression classes. A Variable node depends on itself. All other nodes interior nodes depend on the union of their children’s dependencies (this is all you need to know to document the refined specs for each class). Your implementation must be recursive and, as before, should not do any runtime type checking on Expression s. You are allowed to use Set , HashSet , and/or TreeSet from java.util to implement this. Be aware that the convenient Set.of() methods produce unmodifiable sets, so if you need to add more elements, you’ll need to construct a new set of a concrete class that you can add to.

Optimization

If a formula contains a lot of operations, it can be expensive to evaluate it over and over again (as you might do when graphing a function, for example). But if a subexpression only depends on constants or variables whose values are known and fixed, then the value of that subexpression won’t change with repeat evaluations. Therefore, we can replace the subtree representing that subexpression with a constant node to avoid having to recompute the operations. This is an optimization known as constant folding .

Implement the optimize() method in all of your Expression classes. A Variable can only be optimized if it has an assigned value in the provided variable table, in which case it optimizes to a Constant ; otherwise, it optimizes to itself. An Application or Operation node can be fully optimized to a Constant if its children can all be evaluated to yield a number. But even if a child subtree depends on an unbound variable, the parent node can still be partially optimized by creating a new copy whose children are replaced with their optimized forms. These rules should be sufficient for you to document the refined specs for each class. If you have any doubts about the expected behavior, take a look at the test cases.

As an example, optimizing the expression $(x + 2 \cdot 3) / (y - 1)$ when $y$ is assigned the value $2$ yields the simpler expression $(x + 6)/1$:

Assignment metadata

You’ve made great progress! At this point, you can fill in some of the fields in “reflection.txt”. Enter your name and NetID (both partners if working in a group), then answer the verification questions using RpnCalc .

Part IV: Spreadsheet evaluator

Now that you have a working RPN expression evaluator, let’s put it to work evaluating spreadsheet formulas. The CsvEvaluator application should read the rows and columns of a spreadsheet saved in a CSV file and copy them in CSV format to System.out . But when it encounters a cell whose value starts with an equals sign, = , it should parse the remainder of that cell’s value as an RPN formula, evaluate it, and print that value instead. If the formula cannot be evaluated for any reason, it should be replaced by #N/A in the output.

A spreadsheet formula may refer to values in other cells by using their column–row coordinates as variables in the expression. For example, the formula in the Excel screenshot at the start of this handout would be written as =A1 B1 + , where A1 refers to the cell in the first column (A) of the first row, while B1 refers to the cell in the second column (B) of the first row. Formulas may refer to cells containing either numbers or other formulas, but for simplicity, a formula may only refer to cells on previous rows or cells on the same row but in previous columns (lifting this restriction requires computing a “topological ordering” of formulas, which you will learn how to do later in the course).

Here is an example of the program’s input and output, shown as tables (the row and column headers would not be included in the CSV output):

The main() method of CsvEvaluator has been written for you. Your task is to implement evaluateCsv() according to its specifications. But in order to do so, you’ll first want a helper function to convert between column numbers and column letters.

Column labels

Traditionally, spreadsheet columns are labeled by letters, rather than numbers. The first column is labeled ‘A’, the second column is labeled ‘B’, etc. If more than 26 columns are used, a second letter is added: ‘AA’ is 27, ‘AB’ is 28, and so on. To convert a column position into its label, we need to represent the number in this base-26 numeral system. But because there is no letter corresponding to 0, the process is a little bit different.

Expressing integers in different bases is a classic (exam) problem with a recursive solution. First, the number $n$ is divided by the base $b$, yielding an integer quotient $q$ and a remainder $r$. These obey the relationship $n = q b + r$, subject to $0 \leq r \leq b-1$. The ones digit of the representation is then the remainder $r$, and the rest of the digits are simply the base-$b$ representation of the quotient, $q$. The base case is when the quotient is 0, in which case no more digits should be written to the left.

But the column labeling scheme is what’s known as a “ bijective numeral system ”, which do not use a 0 digit (the number 0 itself is written as the empty string). The algorithm is very similar to that for positional notation, except that the “quotient” $q^\prime$ is defined slightly differently: it is the largest integer that, when multiplied by the base $b$, is strictly less than $n$ (recall that a normal quotient is the largest integer that, when multiplied by $b$, is less than or equal to $n$). The relationship between the quotient and remainder is the same as before, meaning that now $1 \leq r^\prime \leq b$.

With this in mind, implement colToLetters() to recursively convert column positions to labels. Note that this will require converting integers to characters; thankfully, Latin letters in alphabetical order correspond to consecutive integers in Unicode. Therefore, to find, e.g., the 5th letter in the alphabet (which is 4 letters after ‘A’), one can write (char)('A' + 4) .

Working with CSV files

As mentioned in A3, writing a robust parser for CSV files requires a lot of attention to detail in order to accommodate strings that contain commas or newlines. Rather than reinventing the wheel, we should take advantage of solutions that other programmers have already written and tested. To do so, this assignment includes a third-party dependency , a free and open-source class library named “ Apache Commons CSV ”.

CsvEvaluator has already done the work of setting up this library and creating a CSVParser to read the user’s input file and a CSVPrinter to print a CSV file to the console. Your solution will need to iterate over the rows and cells of the input (each row is an instance of CSVRecord ) and print rows of cells to the printer.

While you may use any of the methods provided by these classes, the following ones are sufficient to get the job done:

Note that, unlike in A3, there is no need to read the whole file into a list-of-lists or equivalent data structure. Since formulas can only depend on previous cells, you can write each cell as soon as you have read it. This approach is known as “ online ” processing.

The included CsvEvaluatorTest provides reasonably good coverage of both colToLetters() and evaluateCsv() . It also comments on cases that are known to not be covered by these tests. It is up to you to determine which of these situations might pose a risk to your implementation and to add additional tests as appropriate. You do not need to submit these tests, but that does not make them any less essential to confidently delivering a working solution.

For an end-to-end test of the whole application, try running it with the program argument “pizza.csv”. The output should match the contents in “pizza-out.csv”.

Part V: Challenge extensions

The last few points of the assignment are reserved for challenge tasks. These require a significant amount of effort for relatively few points and are intended as additional exercise for students who complete the rest of the assignment ahead of schedule. It is okay to attempt none of the challenge tasks ; they are not included in the recommended schedule. If you do not want to attempt a challenge, there is no need to upload the corresponding file.

Alternative VarTable implementation (3 points)

You have used the MapVarTable class when writing test cases for expression nodes and when implementing the calculator and spreadsheet evaluator. As its name suggests, it is implemented using a Java HashMap . But the methods in Expression accept any implementation of the VarTable interface, meaning you can use an alternative class instead.

Implement a class named TreeVarTable that implements the VarTable interface using a binary search tree data structure (see Chapter 26). All related code must go in the file “TreeVarTable.java” and must be appropriately documented. You must implement your own tree from scratch (using Java’s TreeMap does not qualify, nor may you copy-paste the textbook or lecture demo implementations). Be sure to test your class thoroughly with a JUnit test suite (which you do not need to submit). Your class must have a default constructor that yields an empty map.

You may use your TreeVarTable class instead of MapVarTable throughout the rest of the assignment (as a form of end-to-end testing), but we do not necessarily recommend submitting this, as any bugs in your TreeVarTable would then count against the code that depends on it.

Additional calculator functionality (2 points)

Implement the following additional features in RpnCalc , replacing their corresponding TODOs:

tabulate <var> <lo> <hi> <n> [<expr>] : Evaluate the current expression ( expr if provided, otherwise the previously set expression) n times, varying the value of variable var between lo and hi . Print a line for each evaluation containing the current value of var followed by the value of the expression.

Example—tabulate the expression $x^2$ for $x$ in the range of 0 to 4:

After executing this command, var should have the value hi .

def <name> <var> [<expr>] : Define a new function named name that will evaluate the current expression ( expr if provided, otherwise the previously set expression) with variable var set to the function’s argument. This function can then be used in future expressions. Unlike variables, functions may not be redefined (attempting to do so is a user error and should be reported as such). Additionally, an expression used to define a function may not depend on any variables other than var (the def command handler should check this).

Example—define a function sqr() that squares its argument, then use it in an expression:

If the user makes an error in invoking one of these commands, your command handler should print a helpful error message to System.err and return (it should not propagate any exceptions). Note that Scanner ’s exceptions are unchecked, so you’ll need to study its documentation to know what to catch.

Return to “reflection.txt”, estimate the amount of time you spent on this assignment, and answer the reflection question. Then submit the following files:

  • Variable.java
  • Application.java
  • Operation.java
  • ExpressionTest.java
  • RpnParser.java
  • CsvEvaluator.java
  • reflection.txt
  • RpnCalc.java (no need to submit if not attempting challenge extension)
  • TreeVarTable.java (no need to submit if not attempting challenge extension)

You hopefully wrote additional test cases for RpnParser and CsvEvaluator to improve your confidence in your solution, but those tests will not be submitted.

Smoketesting

The smoketester will check the following:

  • Your Expression classes, ExpressionTest suite, and RpnParser will be compiled together, since constructors are not part of the Expression interface.
  • Does your ExpressionTest suite pass when used to test your own implementations of the Expression classes?
  • Does your RpnParser pass the test cases included in the release code?
  • What is the output of RpnCalc when executing the commands in “calc-commands.txt”?
  • Does your CsvEvaluator pass the test cases included in the release code?
  • What is the output of CsvEvaluator when evaluating “pizza.csv”, and does it differ from “pizza-out.csv”?

When it comes time to grade your submission, the autograder will additionally check at least the following:

  • Do your implementations of the Expression classes, as created by RpnParser , pass our full test suite?
  • Do your RpnParser , RpnCalc , and CsvEvaluator pass our full test suites?
  • Do your challenge extensions pass our corresponding test suites?

As usual, manual grading will check for compliance with implementation constraints as well as adherence to good coding style.

  • CBSSports.com
  • Fanatics Sportsbook
  • CBS Sports Home
  • NCAA Tournament
  • W. Tournament
  • Champions League
  • Motor Sports
  • High School
  • Horse Racing 

mens-brackets-180x100.jpg

Men's Brackets

womens-brackets-180x100.jpg

Women's Brackets

Fantasy Baseball

Fantasy football, football pick'em, college pick'em, fantasy basketball, fantasy hockey, franchise games, 24/7 sports news network.

cbs-sports-hq-watch-dropdown.jpg

  • CBS Sports Golazo Network
  • March Madness Live
  • PGA Tour on CBS
  • UEFA Champions League
  • UEFA Europa League
  • Italian Serie A
  • Watch CBS Sports Network
  • TV Shows & Listings

The Early Edge

201120-early-edge-logo-square.jpg

A Daily SportsLine Betting Podcast

With the First Pick

wtfp-logo-01.png

NFL Draft is coming up!

  • Podcasts Home
  • Eye On College Basketball
  • The First Cut Golf
  • NFL Pick Six
  • Cover 3 College Football
  • Fantasy Football Today
  • Morning Kombat
  • My Teams Organize / See All Teams Help Account Settings Log Out

2024 March Madness TV schedule, announcers: How to watch NCAA Tournament, tipoff times, TV channels, bracket

The complete television and streaming schedule for how to watch march madness 2024.

usatsi-20244677-1.jpg

The 2024 NCAA Tournament has begun with the opening day of first-round action in the books. What was once a 68-team field has been whittled down to 48 with 16 more teams set to be eliminated Friday as the first round wraps up at five site sacross the nation.

The Big Dance continues Friday at 12:15 ET on CBS as No. 9 seed Northwestern seeks to take down last season's Cinderella favorite, No. 8 seed FAU. As usual, in addition to CBS, this men's NCAA Tournament will air on three other networks (TBS, TNT and truTV). Each station will air four games on Friday.

One major change this year: A new voice of the Final Four. Veteran ace announcer Ian Eagle steps in as the lead play-by-play announcer, replacing the legend, Jim Nantz, who stepped away in 2023. Eagle will be alongside mainstays Bill Raftery, Grant Hill and reporter Tracy Wolfson on CBS' and TBS' top announcing team. 

A longtime staple of NCAA Tournament coverage, Eagle will not be alone as someone stepping into a new role on the team. Former Purdue star Robbie Hummel joins the NCAA Tournament broadcast squad for the first time as an analyst across first- and second-round action.

CBS and TBS lead the way televising 21 games apiece during the NCAA Tournament, while truTV and TNT are carrying 13 and 12, respectively. In addition to the March Madness Live app , where you can watch every game,  Paramount+ subscribers will be able to watch all the games televised by CBS, while subscribers to Max's B/R Sports Add-On can catch the remainder of the games.

From the Selection Show all the way until the playing of "One Shining Moment" after a champion is crowned, CBS Sports and TNT Sports will be bringing you the magic.

Let's take a look at the 2024 March Madness announcing teams as well as the complete schedule for the 2024 NCAA Tournament.

2024 March Madness announcing teams

Play-by-Play | Analyst(s) || Reporter * Regional Weekend announce teams

  • Ian Eagle | Bill Raftery, Grant Hill || Tracy Wolfson*
  • Brian Anderson | Jim Jackson || Allie LaForce*
  • Kevin Harlan | Dan Bonner, Stan Van Gundy || Andy Katz*
  • Andrew Catalon | Steve Lappas || Evan Washburn*
  • Lisa Byington | Steve Smith, Robbie Hummel || Lauren Shehadi
  • Spero Dedes | Jim Spanarkel || Jon Rothstein
  • Tom McCarthy | Deb Antonelli, Avery Johnson || AJ Ross
  • Brad Nessler | Brendan Haywood || Dana Jacobson

2024 NCAA Tournament schedule, dates

First round.

Friday, March 22 Barclays Center -- Brooklyn | Gainbridge Fieldhouse -- Indianapolis | FedEx Forum -- Memphis | Spokane Veterans Memorial Arena -- Spokane

Second round

Saturday, March 23 Spectrum Center -- Charlotte | CHI Health Center -- Omaha | PPG Paints Arena -- Pittsburgh | Delta Center -- Salt Lake City

Sunday, March 19 -- 12:10 p.m. start (CBS, TBS, TNT, truTV) Barclays Center -- Brooklyn | Gainbridge Fieldhouse -- Indianapolis | FedEx Forum -- Memphis | Spokane Veterans Memorial Arena -- Spokane

Thursday, March 28 -- 6:30 p.m. start (CBS, TBS) TD Garden -- Boston | Crypto.com Arena -- Los Angeles

Friday, March 29 -- 6:30 p.m. start (CBS, TBS) American Airlines Center -- Dallas | Little Caesars Arena -- Detroit

Elite Eight

Saturday, March 30 -- 6:09 p.m. start (TBS) TD Garden -- Boston | Crypto.com Arena -- Los Angeles Sunday, March 31 -- 2:20 p.m. start (CBS) American Airlines Center -- Dallas | Little Caesars Arena -- Detroit

Saturday, April 6 -- 6:09 p.m. start (TBS) State Farm Stadium -- Glendale, Arizona

National Championship

Monday, April 8 -- 9:20 p.m. (TBS) State Farm Stadium -- Glendale, Arizona

Our Latest College Basketball Stories

ncaa-march-madness-banner-logo-g.png

2024 NCAA Tournament schedule, dates, times

Gary parrish • 4 min read.

generic-nba-basketball.jpg

Colorado vs. Florida odds, NCAA Tournament picks

Cbs sports staff • 3 min read.

snudda-collins-ole-miss.jpg

Ole Miss forward Collins stepping away from team

Jack maloney • 1 min read.

jaredbutlerbaylor-1.jpg

Auburn vs. Yale odds, NCAA Tournament picks, best bets

printable-ncaa-tournament-bracket-2024.jpg

Print your 2024 NCAA Tournament bracket

David cobb • 2 min read, new mexico vs. clemson odds, 2024 ncaa tournament picks.

c what does assignment return

2024 NCAA Tournament: How to watch live, TV tip times

c what does assignment return

Expert picks: Who wins Friday's games

c what does assignment return

Storylines: Kolek returns for Marquette

c what does assignment return

Heat on UK's Calipari after early exit

c what does assignment return

Kentucky makes another early March Madness exit

c what does assignment return

Michigan State, UNC advance for second-round clash

c what does assignment return

Transfer portal: Ranking top players looking to leave

c what does assignment return

Oakland's Gohlke hits 10 3-pointers in win vs. UK

c what does assignment return

LeBron James gifts Duquesne new sneakers

c what does assignment return

Winners and losers: SEC stumbles out the gate

  • Election 2024
  • Entertainment
  • Newsletters
  • Photography
  • Personal Finance
  • AP Buyline Personal Finance
  • Press Releases
  • Israel-Hamas War
  • Russia-Ukraine War
  • Global elections
  • Asia Pacific
  • Latin America
  • Middle East
  • March Madness
  • AP Top 25 Poll
  • Movie reviews
  • Book reviews
  • Personal finance
  • Financial Markets
  • Business Highlights
  • Financial wellness
  • Artificial Intelligence
  • Social Media

NY state asks court not to let Trump forgo $454M bond during fraud case appeal

Donald Trump is hurtling toward a Monday deadline to secure a financial guarantee on the more than $454 million he owes the state in a civil fraud lawsuit brought by New York’s attorney general Letitia James.

FILE - Former President Donald Trump speaks after exiting the courtroom for a break at New York Supreme Court, Dec. 7, 2023, in New York. New York State Lawyers urged an appeals court Wednesday, March 20, 2024, not to buy Trump's claims that he cannot find a way to post a bond fully covering a $454 million civil fraud judgment while he appeals. (AP Photo/Eduardo Munoz Alvarez, File)

FILE - Former President Donald Trump speaks after exiting the courtroom for a break at New York Supreme Court, Dec. 7, 2023, in New York. New York State Lawyers urged an appeals court Wednesday, March 20, 2024, not to buy Trump’s claims that he cannot find a way to post a bond fully covering a $454 million civil fraud judgment while he appeals. (AP Photo/Eduardo Munoz Alvarez, File)

  • Copy Link copied

NEW YORK (AP) — New York state lawyers urged an appellate court Wednesday not to buy former President Donald Trump’s claims that it’s impossible to post a bond fully covering a $454 million civil fraud judgment while he appeals.

The presumptive Republican nominee’s lawyers said earlier this week that he couldn’t find an underwriter willing to take on the entire amount. But the state is arguing that Trump and his co-defendants didn’t explore every option.

The “defendants fail to propose a serious alternative to fully secure the judgment,” Dennis Fan, a lawyer in the state attorney general’s office, wrote in papers sent to the appeals court.

He suggested those alternatives could include dividing the total among multiple bonds from different underwriters — or letting a court hold some of Trump’s real estate while he appeals. The ex-president is challenging a judge’s ruling last month that he, his company and key executives inflated his wealth on financial statements that were used to get loans and insurance.

One of Trump’s attorneys, Christopher Kise, said in a statement that the papers showed Attorney General Letitia James’ “continued willingness to misrepresent the facts and misconstrue applicable law in her political crusade” against Trump. James is a Democrat, and Trump has repeatedly cast her as a partisan official trying to dent his campaign.

FILE - Republican presidential candidate former President Donald Trump speaks at a campaign rally, March 9, 2024, in Rome Ga. Trump's lawyers kept pressing an appellate court Wednesday, March 20, to excuse him from covering a $454 million fraud lawsuit judgment for now, saying he'd suffer “irreparable harm" before his appeal is decided. (AP Photo/Mike Stewart, File)

In a radio interview early Wednesday, Trump reiterated his complaints about the case, the judgment and the bond requirement.

“They don’t even give you a chance to appeal. They want you to put up money before the appeal. So if you sell a property or do something, and then you win the appeal, you don’t have the property,” Trump said on WABC’s “Sid & Friends In The Morning.”

Under the judgment , Trump needs to pay more than $454 million in penalties and ever-growing interest; some of his co-defendants owe additional money. So far, courts have said that if the former president wants to delay collection while he appeals, he’ll have to post a bond for his entire liability .

Trump said last year that he has “fairly substantially over $400 million in cash.” But he’s now facing more than $543 million in personal legal liabilities from judgments in the civil fraud case, brought by James, and in two lawsuits brought by writer E. Jean Carroll . The advice columnist said Trump sexually assaulted her in the 1990s, then defamed her after she came forward in 2019.

He denies all the allegations.

Trump recently posted a $91.6 million appeal bond to cover the judgment, plus interest, in one of Carroll’s suits. In the other, he put over $5 million in escrow while he appeals.

But in a court filing Monday, Trump’s lawyers asked the state’s intermediate appeals court to excuse him from having to post a bond for the $454 million judgmen t in the business fraud case.

The attorneys wrote that “it is not possible under the circumstances presented.” They said underwriters insisted on cash or other liquid assets instead of real estate as collateral, which would have to cover 120% of the judgment, or more than $557 million.

Insurance broker Gary Giulietti — a Trump golf buddy who handles some of his company’s insurance needs and testified for him in the fraud trial — wrote in a sworn statement that “a bond of this size is rarely, if ever, seen.” The few provided go to huge public companies, Giulietti said. Trump’s company is private.

But Fan, the lawyer in the attorney general’s office, wrote Wednesday that “there is nothing unusual about even billion-dollar judgments being fully bonded on appeal,” citing a handful of cases. They largely involved publicly traded companies.

Fan asked the appeals court to turn down Trump’s request to hold off collection, without a bond, while he appeals.

If the appeals court doesn’t intervene, James can start taking steps March 25 toward enforcing the judgment. The attorney general has said she will seek to seize some of Trump’s assets if he can’t pay.

Associated Press writers Michael R. Sisak and Jill Colvin contributed.

c what does assignment return

SpaceX Starship disintegrates after completing most of third test flight

SpaceX's next-generation Starship spacecraft makes it�s third launch

ENGINEERING GOALS

The Reuters Daily Briefing newsletter provides all the news you need to start your day. Sign up here.

Reporting by Joe Skipper in Boca Chica, Texas, Steve Gorman in Los Angeles and Joey Roulette in Washington; Writing by Steve Gorman; Editing by Will Dunham and Chizu Nomiyama

Our Standards: The Thomson Reuters Trust Principles. , opens new tab

Launch of Russian Soyuz MS-25 spacecraft canceled at last minute

Air Europa says customer data may have been compromised in October breach

Spanish airline Air Europa said on Friday personal data of its customers may have been compromised in a security incident that was detected in October last year.

Illustration shows Apple logo

Dell workers can stay remote — but they're not going to get promoted

  • Dell's strict new RTO mandate excludes fully remote workers from promotion. 
  • Some live hours from offices and say they would now have to move states to advance their careers.
  • The policy is disproportionately affecting women, one employee with access to staff data told BI. 

Insider Today

Dell has had a hybrid working culture in place for more than a decade — long before the pandemic struck.

"Dell cared about the work, not the location," a senior employee at Dell who's worked remotely for more than a decade, told Business Insider last month. "I would say 10% to 15% of every team was remote."

That flexibility has enabled staff to sustain their careers in the face of major life changes, several employees told BI. It has also helped Dell to be placed on the "Best Place to Work for Disability Equality Index" since 2018.

But in February Dell introduced a strict return-to-office mandate, with punitive measures for those who want to stay at home.

Under the new policy, staff were told that from May almost all will be classified as either "hybrid," or "remote."

Hybrid workers will be required to come into an "approved" office at least 39 days a quarter — the equivalent of about three days a week, internal documents seen by BI show.

If they want to keep working from home, staff can opt to go fully remote. But that option has a downside: fully remote workers will not be considered for promotion, or be able to change roles.

The memo states: "For remote team members, it is important to understand the trade-offs: Career advancement, including applying to new roles in the company, will require a team member to reclassify as hybrid onsite."

"The entire company has been complaining about this behind closed doors," said one Dell staffer, who works alongside senior management. The employee asked to remain anonymous for fear of reprisals.

Dell told BI in a statement that "in-person connections paired with a flexible approach are critical to drive innovation and value differentiation."

The approach differs from founder and CEO Michael Dell's previous support for remote workers.

In 2021, he told CRN that the company's expanded homeworking culture was "absolutely here to stay." The billionaire later criticized companies that were enforcing RTO, writing on LinkedIn: "If you are counting on forced hours spent in a traditional office to create collaboration and provide a feeling of belonging within your organization, you're doing it wrong."

His office did not respond to a request for comment from BI.

By 2022, the company line had not changed: "A long-term ambition for Dell Technologies is for 60% of our workforce to operate remotely on any given day."

But in March 2023, Dell started to change its policies with a new mandate ordering all staff living within an hour of offices to come in at least three days a week, CRN reported.

Professor Cary Cooper, an organizational psychologist and cofounder of the National Forum for Health and Wellbeing at work, says Dell's pivot could be a "panicked reaction to a world economy that's not very buoyant."

"When that occurs, people turn inwards. They think, maybe if we brought everybody in, it'll make a difference. We'll perform better," Cooper told BI.

"Senior execs somehow think that people in the office are more productive than at home, even though there's no evidence to back that up."

There's also a "pack mentality" at play, says Cooper, with tech companies trying to follow what everybody else is doing, rather than continue with what has worked for them.

"First on the chopping block"

Frustrated workers at Dell spoke out anonymously to BI about how the new policy will affect them.

One said: "We're being forced into a position where either we're going to be staying as the low man on the totem pole, first on the chopping block when it comes to workforce reduction, or we can be hybrid and go in multiple days a week, which really affects a lot of us."

The staffer said she and many colleagues were hired on remote contracts during the pandemic.

The Dell worker lives about a 45-minute drive from the nearest office and works 10-hour shifts four days a week. However, traveling there would be virtually impossible given she no longer drives following a car crash.

Related stories

She said many of her colleagues would find it very challenging to get to the office three days a week.

'Approved' offices

One Dell worker is already feeling the effects of the new policy.

Dell's list of "approved" sites includes 17 offices in the US and 26 globally — but not the senior employee's nearest office. "I now know I have no office. So I am remote, or I move if I want to stay."

BI has viewed a promotion offer sent to the long-serving remote worker around the same time as the RTO mandate was announced.

To accept that promotion, the employee would not only have to start coming into the office, but move state to be near an "approved" site.

Geographically divided teams

Employees also say that Dell's claims about fostering "in-person connection" do not add up.

It is common for teams at Dell to be spread around the US and even other countries, according to BI's senior source at Dell, who works across the organization and has access to employee data.

"Every team has people in at least two states, some in three or four. I can't think of one team where everyone is in one location," the person said.

That means that even if commuting distances are feasible, many won't be able to collaborate face-to-face with their teams in the same office.

Another Dell worker told BI: "I would support that if I actually had team members that were local and would actually go on-site. With us being so spread out around the United States, there's really no point in us going in. I'm going to be in a room with a bunch of people who don't know how to do my job or how to help me."

Disproportionate impact

BI's senior source at Dell used their access to pull data about the composition of remote teams.

"I deal with many many teams across our business. Every team I work with has at least one person if not two or three affected by this policy," said the senior source at Dell.

"They are overwhelmingly women. This new policy on its face appears to be anti-remote, but in practice will be anti-woman."

"Quiet firing"

Workers who spoke to BI also said they believe the new measures are a way to push some employees out — a phenomenon known as "quiet firing."

"This level of micromanagement makes me want to leave Dell," one said, adding that since the announcement was made, dozens of staff have been discussing quitting in Discord chats.

Two other staff including one based in Germany who spoke to BI also said many people were now considering leaving Dell.

In February last year, Dell laid off about 5% of its workforce, or about 6,600 jobs, per an SEC filing, in the wake of poor PC sales.

"It's not about culture. Period," the senior Dell worker agreed. "There are headcount cuts that need to happen and we are suffering. If people leave on their own, they don't have to pay out severance."

Cooper agreed that the level of control in this policy would result in some resignations.

"An important source of ill health in the workplace is people feeling they don't have control and autonomy over their job," he said. "If they're downsizing, maybe they're saying, well, the people who are not prepared to come into the office. Well, they can go elsewhere."

Dell's move is one of the most abrupt changes to remote work policies largely introduced when the pandemic struck. Its progress will contribute to the debate over the future of work and whether working culture will evolve for good.

Are you a worker at Dell or another company pushing staff back to the office? Contact this reporter at [email protected]

Watch: Microsoft's chief brand officer, Kathleen Hall, says the company's employees are its best product testers

c what does assignment return

  • Main content

IMAGES

  1. CPP-return-statement.png

    c what does assignment return

  2. Assignment Operators in C

    c what does assignment return

  3. Assignment Operators in C Example

    c what does assignment return

  4. Assignment Operators in C++

    c what does assignment return

  5. Assignment Operators in C

    c what does assignment return

  6. C programming tutorials for Beginners

    c what does assignment return

VIDEO

  1. NPTEL Problem Solving through Programming in C ASSIGNMENT 6 ANSWERS 2024

  2. Augmented assignment operators in C

  3. Assignment Operator in C Programming

  4. program to store students record using structure C++

  5. C# Programming Challenge: Customer Classes Part 1 (inheritance, C# OOP, object arrays, Properties)

  6. Introduction to Programming in C Week 2 Assignment Answers 2024 |@OPEducore

COMMENTS

  1. c

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

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

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

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

  4. Assignment Operators in C

    This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: (a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11. 3. "-=" This operator is combination of '-' and '=' operators.

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

  6. Low level details of C/C++ assignment operator implementation. What

    The assignment operators in C and C++ return the value of the variable being assigned to, i.e., their left operand. In your example of a = b, the value of this entire expression is the value that is assigned to a (which is the value of b converted into the type of a ). So you can say that the assignment operator "returns" the value of its left ...

  7. 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. it is equivalent to E1 = T{E2}

  8. 4.6: Assignment Operator

    This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left. Example: (a -= b) can be written as (a = a - b) If initially value 8 is stored in the variable a, then (a -= 6) is equal to 2. (the same as a = a - 6)

  9. C Assignment Operators

    Summary: in this tutorial, you'll learn about the C assignment operators and how to use them effectively. Introduction to the C assignment operators. An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:

  10. The assignment operator

    We execute "A = the reference to B" and return a reference to A. If the assignment operator did not return anything at all, we could not have chained assignment statements, which are part of the overall C++ language. What this example does is more or less exactly what the default assignment operator would do for use anyway.

  11. Assignment operators

    The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). ... In ANSI C, the result of an assignment expression isn't an l-value. That means the legal C++ expression (a += b) += c isn't allowed in C. See ...

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

  13. Assignment Operator in C

    Here is a list of the assignment operators that you can find in the C language: Simple assignment operator (=): This is the basic assignment operator, which assigns the value on the right-hand side to the variable on the left-hand side. Example: int x = 10; // Assigns the value 10 to the variable "x". Addition assignment operator (+=): This ...

  14. What is the benefit of having the assignment operator return a value?

    The equivalent to a = b = c isn't a = c; b = c, it's b = c; a = b. This avoids duplication of side effects and also keeps the modification of a and b in the same order. Also, all these hardware-related arguments are kind of stupid: Most languages are not system languages and are neither designed to solve these problems nor are they being used ...

  15. Operators in C

    C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.

  16. Structure Assignment (GNU C Language Manual)

    15.13 Structure Assignment. Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example: Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

  17. return statement

    a destructor, or. a function-try-block for a function with the return type (possibly cv-qualified) void. without encountering a return statement, return; is executed. If control reaches the end of the main function, return0; is executed. Flowing off the end of a value-returning function, except main and specific coroutines (since C++20 ...

  18. 21.12

    C++ allows self-assignment: int main() { Fraction f1 { 5, 3 }; f1 = f1; // self assignment return 0; } 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 ...

  19. Assignment Operators In C++

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

  20. Return Statement in C

    C return statement ends the execution of a function and returns the control to the function from where it was called. The return statement may or may not return a value depending upon the return type of the function. For example, int returns an integer value, void returns nothing, etc. In C, we can only return a single value from the function ...

  21. c++

    The return type is important for chaining operations. Consider the following construction: a = b = c;. This should be equal to a = (b = c), i.e. c should be assigned into b and b into a. Rewrite this as a.operator= (b.operator= (c)). In order for the assignment into a to work correctly the return type of b.operator= (c) must be reference to the ...

  22. Assignment 4: Formula evaluation (CS 2110 Spring 2024)

    Assignment 4: Formula evaluation. Programming languages give us as programmers the ability to evaluate mathematical expressions like a calculator, including expressions that involve variables. The language's compiler translates the formula into instructions that a computer's CPU can execute. ... Day 4: Part III—Return to your Expression ...

  23. 2024 March Madness TV schedule, announcers: How to watch NCAA

    The First Four is a wrap and that means the NCAA Tournament as we know and love it at its best figure is set. Sixty-four teams, the perfect number, and it only lasts for about 14 hours before the ...

  24. Trump's social media company gets the greenlight to go public

    Trump's return to the stock market could be right around the corner. All eyes are on a vote Friday by shareholders of Digital World Acquisition Corp., a shell company that is looking to merge with the former president's media business. (AP Photo/Wilfredo Lee, File) Share. Share Copy. Link copied. Email Facebook; X ...

  25. NY state asks court not to let Trump forgo $454M bond

    FILE - Former President Donald Trump speaks after exiting the courtroom for a break at New York Supreme Court, Dec. 7, 2023, in New York. New York State Lawyers urged an appeals court Wednesday, March 20, 2024, not to buy Trump's claims that he cannot find a way to post a bond fully covering a $454 million civil fraud judgment while he appeals.

  26. c++

    And it is a ++ operator, so semantically it must increment it's operand and then return reference to that operand. So you must do two actions: // Assign new value to the t. t = Traficlight::yellow; // Return rusult. return t; This can be written in one line because assignment operator returns the assigned value.

  27. SpaceX Starship disintegrates after completing most of third test

    SpaceX's Starship rocket, designed to eventually send astronauts to the moon and beyond, completed nearly an entire test flight through space on its third try on Thursday, getting farther than ...

  28. c++

    Copy assignment should not return rvalue reference cos it may have the assigned object moved. Again take the assignment chain for example. a = b = c; // if a has a copy assignment overload that takes rvalue reference as argument like the following. X& operator=(X &&);

  29. Dell workers can stay remote

    Dell's strict new RTO mandate excludes fully remote workers from promotion, abandoning years of flexible working, and some employees are not happy.

  30. Returning a struct containing array in C

    Or is it better to use memcpy instead of assignment if I care about performance? - nirki. Mar 17 at 14:31. ... C 1990 allows declaring functions that return structures containing arrays, but why do you ask? Are you writing new code that needs to conform to the 1990 C standard? You should not be using the 1990 C standard in new code unless it ...