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 - Scope Rules
  • C - Pointers
  • C - Strings
  • C - 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 −

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

7 Assignment Expressions

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

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

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

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

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

is equivalent to

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

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

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

cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

[ edit ] Example

Possible output:

[ edit ] Defect reports

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

[ edit ] See also

Operator precedence

Operator overloading

  • 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 25 January 2024, at 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

This browser is no longer supported.

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

Assignment operators

  • 7 contributors

expression assignment-operator expression

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

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

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

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

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

Assignment operators table

Operator keywords.

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

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

Simple assignment

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

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

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

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

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

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

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

the assignment statement

can have one of the following effects:

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

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

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

Compound assignment

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

an arithmetic type

a pointer, if op is + or -

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

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

Result of assignment operators

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

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

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

Submit and view feedback for

Additional resources

freeCodeCamp Challenge Guide: Assignment with a Returned Value

Assignment with a returned value.

Functions act as placeholders for the data they output. Basically, you can assign the output of a function to a variable, just like any normal data.

Solution is very simple of this question: // Example var changed = 0;

function change(num) { return (num + 5) / 3; }

changed = change(10);

// Setup var processed = 0;

function processArg(num) { return (num + 3) / 5; }

// Only change code below this line

processed = processArg(7);

You need to be smart: And follow this formula in assigning a number for **processArg** function (X + 3) / 5 = 2

Hey fellow campers.Everyone is unique when it comes to learning.Use whichever method you find fit to drive the logic home.This is how I did it:

// Example function minusSeven(num) { return num - 7; }

function timesFive(num) { return num * 5; }

var answer = timesFive(5);

Sorry that was for previous challenge.

Here we go:

// Example var changed = 0;

Shahar Mike's Web Spot

Yet another geek's blog

Return Value Optimization

Table of Contents

Return Value Optimization (RVO), Named RVO (NRVO) and Copy-Elision are in C++ since C++98. In this post I will explain what these concepts mean and how they help improve runtime performance.

I will use our old friend Snitch - a class dedicated to printing at key events:

Let’s get goin’.

RVO basically means the compiler is allowed to avoid creating temporary objects for return values, even if they have side effects .

Here’s a simple example:

Output (note that -fno-elide-constructors disables RVO in clang):

In the first run (without -fno-elide-constructors ) the compiler refrained from calling user code despite it having a clear side effect (being printing to console). This is also the default behavior, meaning practically all C++ programs utilize RVO.

Without RVO the compiler creates 3 Snitch objects instead of 1:

  • A temporary object inside ExampleRVO() (when printing c'tor );
  • A temporary object for the returned object inside main() (when printing the first move c'tor );
  • The named object snitch (when printing the second move c'tor ).

Performance

The neat thing about RVO is that it makes returning objects free . It works via allocating memory for the to-be-returned object in the caller’s stack frame. The returning function then uses that memory as if it was in its own frame without the programmer knowing / caring.

In C++98 days this was significant:

217% difference on my machine by simply avoiding the copy of the vector . In C++11 (or newer) environments it is even marginally faster to disable RVO:

This is due to Move Semantics, which is the subject of the next post.

In trying to come up with an example where RVO is faster on modern C++ using STL containers I hit a wall, mostly because of move-semantics but also because on x86_84 RVO is in the ABI so disabling it is harder. Please post such examples if you have any!

Named Return Value Optimization (NRVO)

Named RVO is when an object with a name is returned but is nevertheless not copied. A simple example is:

Which has a similar output to ExampleRVO() above:

While RVO is almost always going to happen, NRVO is more restricted, as we will see below. I personally don’t think NRVO deserves its own acronym.

Copy Elision

RVO is part of a larger group of optimizations called copy-elision . Essentials are the same, except copy-elision is not required to happen as part of return statements, for example:

In my experience, RVO is more frequent (and thus useful) than other copy-elision practices, but your mileage may vary.

When RVO doesn’t / can’t happen

RVO is an optimization the compiler is allowed to apply (starting C++17 it is in fact required to in certain cases). However, even in C++17 it is not always guaranteed. Let’s look at a few examples.

The following examples are cases where, on my environment, RVO doesn’t happen. Some of them may change with other compiler / versions.

Deciding on Instance at Runtime

When the compiler can’t know from within the function which instance will be returned it must disable RVO:

Returning a Parameter / Global

When returning an object that is not created in the scope of the function there is no way to do RVO:

Returning by std::move()

Returning by calling std::move() on the return value is an anti-pattern. It is wrong most of the times. It will indeed attempt to force move-constructor, but in doing so it will disable RVO. It is also redundant, as move will happen if it can even without explicitly calling std::move() (see here ).

RVO can only happen when an object is created from a returned value. Using operator= on an existing object rather than copy/move constructor might be mistakenly thought of as RVO, but it isn’t:

Returning Member

In some cases even an unnamed variable can’t RVO:

While we can’t count on RVO to always take place, it will in most cases. For those cases where it doesn’t we always have Move Semantics, which is the topic of the next post . As always, optimize for readability rather than performance when writing code, unless you have a quantifiable reason.

  • 90% Refund @Courses
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Related Articles

  • Solve Coding Problems
  • Continue Statement in C
  • Break Statement in C
  • C if else if ladder
  • Structure of the C Program
  • while loop in C
  • Basic Code Optimizations in C
  • C Programming Language Standard
  • Local Variable in C
  • do...while Loop in C
  • Data type of case labels of switch statement in C++?
  • Initialization of global and static variables in C
  • Keywords in C
  • Jump Statements in C
  • Newline in C
  • Global Variables in C
  • C Basic Syntax
  • 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++?.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now !

Please Login to comment...

Improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

Learn C++

2.2 — Function return values (value-returning functions)

Consider the following program:

This program is composed of two conceptual parts: First, we get a value from the user. Then we tell the user what double that value is.

Although this program is trivial enough that we don’t need to break it into multiple functions, what if we wanted to? Getting an integer value from the user is a well-defined job that we want our program to do, so it would make a good candidate for a function.

So let’s write a program to do this:

While this program is a good attempt at a solution, it doesn’t quite work.

When function getValueFromUser is called, the user is asked to enter an integer as expected. But the value they enter is lost when getValueFromUser terminates and control returns to main . Variable num never gets initialized with the value the user entered, and so the program always prints the answer 0 .

What we’re missing is some way for getValueFromUser to return the value the user entered back to main so that main can make use of that data.

Return values

When you write a user-defined function, you get to determine whether your function will return a value back to the caller or not. To return a value back to the caller, two things are needed.

First, your function has to indicate what type of value will be returned. This is done by setting the function’s return type , which is the type that is defined before the function’s name. In the example above, function getValueFromUser has a return type of void (meaning no value will be returned to the caller), and function main has a return type of int (meaning a value of type int will be returned to the caller). Note that this doesn’t determine what specific value is returned -- it only determines what type of value will be returned.

Related content

We explore functions that return void further in the next lesson ( 2.3 -- Void functions (non-value returning functions) ).

Second, inside the function that will return a value, we use a return statement to indicate the specific value being returned to the caller. The specific value returned from a function is called the return value . When the return statement is executed, the function exits immediately, and the return value is copied from the function back to the caller. This process is called return by value .

Let’s take a look at a simple function that returns an integer value, and a sample program that calls it:

When run, this program prints:

Execution starts at the top of main . In the first statement, the function call to returnFive is evaluated, which results in function returnFive being called. Function returnFive returns the specific value of 5 back to the caller, which is then printed to the console via std::cout .

In the second function call, the function call to returnFive is evaluated, which results in function returnFive being called again. Function returnFive returns the value of 5 back to the caller. The expression 5 + 2 is evaluated to produce the result 7 , which is then printed to the console via std::cout .

In the third statement, function returnFive is called again, resulting in the value 5 being returned back to the caller. However, function main does nothing with the return value, so nothing further happens (the return value is ignored).

Note: Return values will not be printed unless the caller sends them to the console via std::cout . In the last case above, the return value is not sent to std::cout , so nothing is printed.

When a called function returns a value, the caller may decide to use that value in an expression or statement (e.g. by using it to initialize a variable, or sending it to std::cout ) or ignore it (by doing nothing else). If the caller ignores the return value, it is discarded (nothing is done with it).

Fixing our challenge program

With this in mind, we can fix the program we presented at the top of the lesson:

When this program executes, the first statement in main will create an int variable named num . When the program goes to initialize num , it will see that there is a function call to getValueFromUser() , so it will go execute that function. Function getValueFromUser , asks the user to enter a value, and then it returns that value back to the caller ( main ). This return value is used as the initialization value for variable num .

Compile this program yourself and run it a few times to prove to yourself that it works.

Revisiting main()

You now have the conceptual tools to understand how the main function actually works. When the program is executed, the operating system makes a function call to main . Execution then jumps to the top of main . The statements in main are executed sequentially. Finally, main returns an integer value (usually 0 ), and your program terminates. The return value from main is sometimes called a status code (also sometimes called an exit code , or rarely a return code ), as it is used to indicate whether the program ran successfully or not.

By definition, a status code of 0 means the program executed successfully.

Best practice

Your main function should return the value 0 if the program ran normally.

A non-zero status code is often used to indicate failure (and while this works fine on most operating systems, strictly speaking, it’s not guaranteed to be portable).

For advanced readers

The C++ standard only defines the meaning of 3 status codes: 0, EXIT_SUCCESS, and EXIT_FAILURE. 0 and EXIT_SUCCESS both mean the program executed successfully. EXIT_FAILURE means the program did not execute successfully.

EXIT_SUCCESS and EXIT_FAILURE are preprocessor macros defined in the <cstdlib> header:

If you want to maximize portability, you should only use 0 or EXIT_SUCCESS to indicate a successful termination, or EXIT_FAILURE to indicate an unsuccessful termination.

We cover the preprocessor and preprocessor macros in lesson 2.10 -- Introduction to the preprocessor .

C++ disallows calling the main() function explicitly.

As an aside…

C does allow main() to be called explicitly, so some C++ compilers will allow this for compatibility reasons.

For now, you should also define your main() function at the bottom of your code file, below other functions, and avoid calling it explicitly.

A value-returning function that does not return a value will produce undefined behavior

A function that returns a value is called a value-returning function . A function is value-returning if the return type is anything other than void .

A value-returning function must return a value of that type (using a return statement), otherwise undefined behavior will result.

We discuss undefined behavior in lesson 1.6 -- Uninitialized variables and undefined behavior .

Here’s an example of a function that produces undefined behavior:

A modern compiler should generate a warning because getValueFromUserUB is defined as returning an int but no return statement is provided. Running such a program would produce undefined behavior, because getValueFromUserUB() is a value-returning function that does not return a value.

In most cases, compilers will detect if you’ve forgotten to return a value. However, in some complicated cases, the compiler may not be able to properly determine whether your function returns a value or not in all cases, so you should not rely on this.

Make sure your functions with non-void return types return a value in all cases.

Failure to return a value from a value-returning function will cause undefined behavior.

Function main will implicitly return 0 if no return statement is provided

The only exception to the rule that a value-returning function must return a value via a return statement is for function main() . The function main() will implicitly return the value 0 if no return statement is provided. That said, it is best practice to explicitly return a value from main , both to show your intent, and for consistency with other functions (which will exhibit undefined behavior if a return value is not specified).

Functions can only return a single value

A value-returning function can only return a single value back to the caller each time it is called.

Note that the value provided in a return statement doesn’t need to be literal -- it can be the result of any valid expression, including a variable or even a call to another function that returns a value. In the getValueFromUser() example above, we returned a variable input , which held the number the user input.

There are various ways to work around the limitation of functions only being able to return a single value, which we’ll cover in future lessons.

The function author can decide what the return value means

The meaning of the value returned by a function is determined by the function’s author. Some functions use return values as status codes, to indicate whether they succeeded or failed. Other functions return a calculated or selected value. Other functions return nothing (we’ll see examples of these in the next lesson).

Because of the wide variety of possibilities here, it’s a good idea to document your function with a comment indicating what the return values mean. For example:

Reusing functions

Now we can illustrate a good case for function reuse. Consider the following program:

While this program works, it’s a little redundant. In fact, this program violates one of the central tenets of good programming: Don’t Repeat Yourself (often abbreviated DRY ).

Why is repeated code bad? If we wanted to change the text “Enter an integer:” to something else, we’d have to update it in two locations. And what if we wanted to initialize 10 variables instead of 2? That would be a lot of redundant code (making our programs longer and harder to understand), and a lot of room for typos to creep in.

Let’s update this program to use our getValueFromUser function that we developed above:

This program produces the following output:

In this program, we call getValueFromUser twice, once to initialize variable x , and once to initialize variable y . That saves us from duplicating the code to get user input, and reduces the odds of making a mistake. Once we know getValueFromUser works, we can call it as many times as we desire.

This is the essence of modular programming: the ability to write a function, test it, ensure that it works, and then know that we can reuse it as many times as we want and it will continue to work (so long as we don’t modify the function -- at which point we’ll have to retest it).

Follow DRY: “don’t repeat yourself”. If you need to do something more than once, consider how to modify your code to remove as much redundancy as possible. Variables can be used to store the results of calculations that need to be used more than once (so we don’t have to repeat the calculation). Functions can be used to define a sequence of statements we want to execute more than once. And loops (which we’ll cover in a later chapter) can be used to execute a statement more than once.

Like all best practices, DRY is meant to be a guideline, not an absolute. Reader Yariv has noted that DRY can harm overall comprehension when code is broken into pieces that are too small.

The opposite of DRY is WET (“Write everything twice”).

Return values provide a way for functions to return a single value back to the function’s caller.

Functions provide a way to minimize redundancy in our programs.

Question #1

Inspect (do not compile) each of the following programs. Determine what the program will output, or whether the program will generate a compiler error.

Assume you have “treat warnings as errors” turned off.

Show Solution

1f) Extra credit: Will the following program compile?

Question #2

What does “DRY” stand for, and why is it a useful practice to follow?

guest

c assignment return value

Create a form in Word that users can complete or print

In Word, you can create a form that others can fill out and save or print.  To do this, you will start with baseline content in a document, potentially via a form template.  Then you can add content controls for elements such as check boxes, text boxes, date pickers, and drop-down lists. Optionally, these content controls can be linked to database information.  Following are the recommended action steps in sequence.  

Show the Developer tab

In Word, be sure you have the Developer tab displayed in the ribbon.  (See how here:  Show the developer tab .)

Open a template or a blank document on which to base the form

You can start with a template or just start from scratch with a blank document.

Start with a form template

Go to File > New .

In the  Search for online templates  field, type  Forms or the kind of form you want. Then press Enter .

In the displayed results, right-click any item, then select  Create. 

Start with a blank document 

Select Blank document .

Add content to the form

Go to the  Developer  tab Controls section where you can choose controls to add to your document or form. Hover over any icon therein to see what control type it represents. The various control types are described below. You can set properties on a control once it has been inserted.

To delete a content control, right-click it, then select Remove content control  in the pop-up menu. 

Note:  You can print a form that was created via content controls. However, the boxes around the content controls will not print.

Insert a text control

The rich text content control enables users to format text (e.g., bold, italic) and type multiple paragraphs. To limit these capabilities, use the plain text content control . 

Click or tap where you want to insert the control.

Rich text control button

To learn about setting specific properties on these controls, see Set or change properties for content controls .

Insert a picture control

A picture control is most often used for templates, but you can also add a picture control to a form.

Picture control button

Insert a building block control

Use a building block control  when you want users to choose a specific block of text. These are helpful when you need to add different boilerplate text depending on the document's specific purpose. You can create rich text content controls for each version of the boilerplate text, and then use a building block control as the container for the rich text content controls.

building block gallery control

Select Developer and content controls for the building block.

Developer tab showing content controls

Insert a combo box or a drop-down list

In a combo box, users can select from a list of choices that you provide or they can type in their own information. In a drop-down list, users can only select from the list of choices.

combo box button

Select the content control, and then select Properties .

To create a list of choices, select Add under Drop-Down List Properties .

Type a choice in Display Name , such as Yes , No , or Maybe .

Repeat this step until all of the choices are in the drop-down list.

Fill in any other properties that you want.

Note:  If you select the Contents cannot be edited check box, users won’t be able to click a choice.

Insert a date picker

Click or tap where you want to insert the date picker control.

Date picker button

Insert a check box

Click or tap where you want to insert the check box control.

Check box button

Use the legacy form controls

Legacy form controls are for compatibility with older versions of Word and consist of legacy form and Active X controls.

Click or tap where you want to insert a legacy control.

Legacy control button

Select the Legacy Form control or Active X Control that you want to include.

Set or change properties for content controls

Each content control has properties that you can set or change. For example, the Date Picker control offers options for the format you want to use to display the date.

Select the content control that you want to change.

Go to Developer > Properties .

Controls Properties  button

Change the properties that you want.

Add protection to a form

If you want to limit how much others can edit or format a form, use the Restrict Editing command:

Open the form that you want to lock or protect.

Select Developer > Restrict Editing .

Restrict editing button

After selecting restrictions, select Yes, Start Enforcing Protection .

Restrict editing panel

Advanced Tip:

If you want to protect only parts of the document, separate the document into sections and only protect the sections you want.

To do this, choose Select Sections in the Restrict Editing panel. For more info on sections, see Insert a section break .

Sections selector on Resrict sections panel

If the developer tab isn't displayed in the ribbon, see Show the Developer tab .

Open a template or use a blank document

To create a form in Word that others can fill out, start with a template or document and add content controls. Content controls include things like check boxes, text boxes, and drop-down lists. If you’re familiar with databases, these content controls can even be linked to data.

Go to File > New from Template .

New from template option

In Search, type form .

Double-click the template you want to use.

Select File > Save As , and pick a location to save the form.

In Save As , type a file name and then select Save .

Start with a blank document

Go to File > New Document .

New document option

Go to File > Save As .

Go to Developer , and then choose the controls that you want to add to the document or form. To remove a content control, select the control and press Delete. You can set Options on controls once inserted. From Options, you can add entry and exit macros to run when users interact with the controls, as well as list items for combo boxes, .

Adding content controls to your form

In the document, click or tap where you want to add a content control.

On Developer , select Text Box , Check Box , or Combo Box .

Developer tab with content controls

To set specific properties for the control, select Options , and set .

Repeat steps 1 through 3 for each control that you want to add.

Set options

Options let you set common settings, as well as control specific settings. Select a control and then select Options to set up or make changes.

Set common properties.

Select Macro to Run on lets you choose a recorded or custom macro to run on Entry or Exit from the field.

Bookmark Set a unique name or bookmark for each control.

Calculate on exit This forces Word to run or refresh any calculations, such as total price when the user exits the field.

Add Help Text Give hints or instructions for each field.

OK Saves settings and exits the panel.

Cancel Forgets changes and exits the panel.

Set specific properties for a Text box

Type Select form Regular text, Number, Date, Current Date, Current Time, or Calculation.

Default text sets optional instructional text that's displayed in the text box before the user types in the field. Set Text box enabled to allow the user to enter text into the field.

Maximum length sets the length of text that a user can enter. The default is Unlimited .

Text format can set whether text automatically formats to Uppercase , Lowercase , First capital, or Title case .

Text box enabled Lets the user enter text into a field. If there is default text, user text replaces it.

Set specific properties for a Check box .

Default Value Choose between Not checked or checked as default.

Checkbox size Set a size Exactly or Auto to change size as needed.

Check box enabled Lets the user check or clear the text box.

Set specific properties for a Combo box

Drop-down item Type in strings for the list box items. Press + or Enter to add an item to the list.

Items in drop-down list Shows your current list. Select an item and use the up or down arrows to change the order, Press - to remove a selected item.

Drop-down enabled Lets the user open the combo box and make selections.

Protect the form

Go to Developer > Protect Form .

Protect form button on the Developer tab

Note:  To unprotect the form and continue editing, select Protect Form again.

Save and close the form.

Test the form (optional)

If you want, you can test the form before you distribute it.

Protect the form.

Reopen the form, fill it out as the user would, and then save a copy.

Creating fillable forms isn’t available in Word for the web.

You can create the form with the desktop version of Word with the instructions in Create a fillable form .

When you save the document and reopen it in Word for the web, you’ll see the changes you made.

Facebook

Need more help?

Want more options.

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

c assignment return value

Microsoft 365 subscription benefits

c assignment return value

Microsoft 365 training

c assignment return value

Microsoft security

c assignment return value

Accessibility center

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

c assignment return value

Ask the Microsoft Community

c assignment return value

Microsoft Tech Community

c assignment return value

Windows Insiders

Microsoft 365 Insiders

Was this information helpful?

Thank you for your feedback.

IMAGES

  1. return statement in C/C++ with Examples

    c assignment return value

  2. Main Function Return Value

    c assignment return value

  3. Multiple Parameters and Return Values

    c assignment return value

  4. How To "Return" More Than One Value From A Function

    c assignment return value

  5. Return Statement in C

    c assignment return value

  6. C++ Return by Reference

    c assignment return value

VIDEO

  1. USELESS Return from a Function in C++

  2. meaning of return 0 in c programming

  3. NPTEL Problem Solving Through Programming In C Week 0 Quiz Assignment Solution

  4. Nested if else statement in C programming

  5. Assignment Operator in C Programming

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

COMMENTS

  1. c

    4,681 11 44 46 Add a comment 5 Answers Sorted by: 64 It evaluates to 2 because that's how the standard defines it. From C11 Standard, section 6.5.16: An assignment expression has the value of the left operand after the assignment It's to allow things like this: a = b = c;

  2. Assignment Operators in C

    Assignment Operators in C Read Courses Practice Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value.

  3. Assignment operators

    Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as (a=b)=c are invalid). rhs and lhs must satisfy one of the following: both lhs and rhs have compatible struct or union type, or..

  4. Assignment Operators in C

    Line 1 - = Operator Example, Value of c = 21 Line 2 - += Operator Example, Value of c = 42 Line 3 - -= Operator Example, Value of c = 21 Line 4 - *= Operator Example, Value of c = 441 Line 5 - /= Operator Example, Value of c = 21 Line 6 - %= Operator Example, Value of c = 11 Line 7 - <<= Operator Example, Value of c = 44 Line 8 - >>= Operator Ex...

  5. Assignment Expressions (GNU C Language Manual)

    x = (y = (z = 0)); This is the only useful way for them to associate; the other way, ((x = y) = z) = 0; would be invalid since an assignment expression such as x = yis not valid as an lvalue. Warning:Write parentheses around an assignment if you nest it inside another expression, unless that is a conditional expression,

  6. C Class

    Addition and Subtraction: + and -" a = 1 + 1 sets a to 2 ; b = 3.5 + 2.1 sets b to 5.6 ; c = a - 2 + 1 sets c to whatever is in a less 1, because the statement is evaluated from left to right. If a is set to 4, evaluation would proceed like: a - 2 + 1 4 - 2 + 1 2 + 1 3 Note that the result of an addition overflow (where the result is larger than the maximum value storeable in the variable) is ...

  7. C Assignment Operators

    An assignment operation assigns the value of the right-hand operand to the storage location named by the left-hand operand. Therefore, the left-hand operand of an assignment operation must be a modifiable l-value. ... The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment ...

  8. C Function Arguments and Function Return Values

    C Function Arguments and Function Return Values - GeeksforGeeks C Function Arguments and Function Return Values Read Courses Practice Prerequisite: Functions in C A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions.

  9. Assignment operators

    new-value the expression(until C++11) initializer clause (since C++11) to assign to the target ↑ target-expr must have higher precedence than an assignment expression. ↑ new-value cannot be a comma expression, because its precedence is lower. Simple assignment expression. Compound assignment expression.

  10. Assignment operators

    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.

  11. Learn C Programming

    Assignment by the function return value A function is a statement that can return the result of its execution to its caller. When the function has a data type that is not void, the function is replaced by its returned value, which can then be assigned to a variable of a compatible type.

  12. Assignment operator (C++)

    Return value of overloaded assignment operator. The language permits an overloaded assignment operator to have an arbitrary return type (including void). However, the operator is usually defined to return a reference to the assignee. ... C++ supports assignment between different classes, both via implicit copy constructor and assignment ...

  13. c++

    Actually, the assignment operation itself doesn't depend on the return value - that's why the return type isn't straightforward to understanding. The return type is important for chaining operations. Consider the following construction: a = b = c;.

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

  15. freeCodeCamp Challenge Guide: Assignment with a Returned Value

    function processArg (num) {. return (num + 3) / 5; } // Only change code below this line. processed = processArg (7); 10 Likes. Assignment with a Returned Value Hints Hint 1 Functions act as placeholders for the data they output. Basically, you can assign the output of a function to a variable, just like any normal data.

  16. Return Value Optimization

    Returning by calling std::move() on the return value is an anti-pattern. It is wrong most of the times. It will indeed attempt to force move-constructor, but in doing so it will disable RVO. ... $ clang++ -std=c++11 -stdlib=libc++ main.cpp && ./a.out c'tor c'tor move assignment d'tor d'tor Returning Member. In some cases even an unnamed ...

  17. Return Statement in C

    Return Statement in C Read Courses Practice 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.

  18. c#

    7 While I was working on some of older code in C#, I encountered a code which irked me. Without much ado, it goes something like this: private string foo (string _text) { /* some manipulation on _text */ return _text = Server.HtmlDecode (_text); }

  19. 2.2

    A function that returns a value is called a value-returning function. A function is value-returning if the return type is anything other than void. A value-returning function must return a value of that type (using a return statement), otherwise undefined behavior will result.

  20. Create a form in Word that users can complete or print

    Default Value Choose between Not checked or checked as default. Checkbox size Set a size Exactly or Auto to change size as needed. Check box enabled Lets the user check or clear the text box. Set specific properties for a Combo box. Drop-down item Type in strings for the list box items.

  21. Return value of assignment operator overloading c++

    1 This question already has answers here : What are the basic rules and idioms for operator overloading? (10 answers) Closed 6 years ago. I'm new to C++ and I'm starting with learncpp website. In Assignment Operator Overloading chapter has those lines of code:

  22. javascript

    Ask Question Asked 10 years, 10 months ago Modified 1 year, 7 months ago Viewed 29k times 66 Why does the regular assignment statement (say, x = 5) return the value assigned ( 5 in this case), while the assignment combined with a variable declaration ( var x = 5) returns undefined?