IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

  • C - Getting Started
  • C - Overview
  • C - Advantages & Disadvantages
  • C - Character Set
  • Gcc Vs. G++
  • Why We should Use C?
  • C - Basic Rules
  • C - Comments
  • C - Variable Naming Conventions
  • C - Variable Initialization
  • C - Constants
  • C - Character Constant
  • C - Octal Literals
  • C - Hexadecimal Literals
  • C - Automatic (auto) Variables
  • Local Vs. Global Variables
  • C - Access Global Variables
  • Is exit() & return Statements are Same?
  • C - Print Float Value
  • C - Print Multiple Lines Using printf()
  • C - Argument Index Specification
  • C - Value Returned by scanf()
  • C - Returned Values of printf() & scanf()
  • What do 'lvalue' & 'rvalue' Mean
  • Automatic (auto) Vs. Static Variables

C Data Types

  • C - Data Types & Operators
  • C - Basic Data Types
  • C - 'unsigned char' For Memory Optimization
  • short Vs. short int Vs. int
  • unsigned int Vs. size_t
  • C - Storage Classes Introduction
  • C - Storage Classes With Examples
  • C- Type Conversion
  • C - Type Qualifiers

C Input/Output

  • C - Read String With Spaces
  • C - Input String of Unknown Length
  • C - Disadvantages of scanf()
  • C - scanf() need '%lf' for doubles, when printf() is okay with just '%f'
  • C - Format Specifier for unsigned short int
  • C - printf() Format Specifier for bool
  • C - printf() Arguments for long
  • C - printf() Specifier for double
  • Is there a printf() converter to print in binary format?
  • C - Nested printf()
  • printf() Vs. puts()
  • printf() Vs. sprintf()
  • %d Vs. %i format Specifiers
  • C - Single Character Input & Output
  • C- Formatted Input & Output
  • C - Octal & Hex Escape Sequences
  • C - Convert Float to String
  • gets() Vs. fgets()
  • C - Input Unsigned Integer Value
  • C - Input Octal Value
  • C - Input Hex Value
  • C - Input Decimal, Octal & Hex in char Variables
  • C - Input With '%i'
  • C - Input Individual Characters
  • C - Skip characters While Reading Integers
  • C - Read Memory Address
  • C - Printing Variable's Address
  • C - printf() Examples & Variations

C Operators

  • C - Operators Precedence & Associativity
  • Operators Vs. Operands
  • C - Unary Operators
  • C - Equality Operators
  • C - Logical AND (&&) Operator
  • C - Logical OR (||) Operator
  • C - Logical NOT (!) Operator
  • C - Modulus on Negative Numbers
  • C - Expression a=b=c (Multiple Assignment) Evaluates
  • C - Expression a==b==c (Multiple Comparison) Evaluates
  • C - Complex Return Statement Using Comma Operator
  • C - Comma Operator
  • C - Bitwise Operators
  • C - Bitwise One's Compliment
  • C - Modulus of Float or Double Numbers

C Conditional Statements

  • C - If Else Statements
  • C - Switch Case
  • C - Switch Statements Features, Disadvantages
  • C - Using Range With Switch

C Control Statements

  • C - 'goto' Statement
  • C - break & continue
  • Print Numbers From 1 to N Using goto
  • C - Looping
  • C - Looping Programs
  • C - Nested Loops
  • C - Entry Controlled Vs. Exit Controlled Loops
  • C - Sentinel Vs. Counter Controlled Loops
  • C - Use for Loop as Infinite Loop
  • C - Strings in C language programming
  • C - string.h Functions
  • C - memcpy() Function
  • C - Write Your Own memcpy()
  • C - memset() Function
  • C - Write Your Own memset()

C Functions

  • C - Library & User-define Functions
  • C - Static Functions
  • C - Scope of Function Parameters
  • C - Recursion
  • C - Recursion Examples
  • More on Arrays
  • C - Properties/Characteristics of Array

C Structure and Unions

  • C Structures
  • C - Initialize a Structure in Accordance
  • C - Size of Structure With No Members
  • C -Pointer to Structure
  • C - Nested Structure Initialization
  • C - Nested Structure With Examples
  • C - Size of Structure
  • C - Copy Complete Structure in Byte Array
  • C - Pointer to Union
  • C - Pointers
  • C - Pointer Rules
  • C - Pointers Declarations
  • C - Pointer Address Operators
  • C - Accessing Variable Using Pointer
  • C - Address of (&) & Dereference (*) Operators
  • C - NULL Pointer
  • C - Pointers as Argument
  • C - Pointer Arithmetic
  • C - Pointer to an Array
  • C - Evaluation of Statement '*ptr++'
  • C - Pointer & Non-pointer Variables Declarations Together
  • C - Pointer to an Array of Integers
  • C - Pointer to Pointer
  • C - void Pointer as Function Argument
  • char s[] Vs. char *s
  • C - Copying Integer Value to Char Buffer & Vice Versa
  • C - Call by Reference Vs. Call by Value
  • C - Typedef Function Pointer

C Preprocessor Directives

  • Recommendation for defining a macro in C language
  • Macro expansion directives (#define, #undef) in C language
  • Complex macro with arguments (function like macro) in C language
  • C language #ifdef, #else, #endif Pre-processor with Example
  • C language #if, #elif, #else, #endif Pre-processor with Example
  • Parameterized Macro - we cannot use space after the Macro Name
  • Stringizing Operator (#) in C
  • Token Pasting Directive Operator (##) in C

C Command-line Arguments

  • C language Command Line Arguments

C File Handlings

  • C - Basics of File Handling
  • C - File Handling Programs
  • C - Graphics Modes
  • C - Using Colors in Text Mode
  • C - More on Graphics Modes
  • C - OUTTEXTXY() & SETTEXTSTYLE() Functions
  • C - Draw Circle & Rectangle
  • C - graphics.h Functions
  • C - More Graphics-related Interesting Functions

C Advance Topics

  • C - Process Identification (pid_t)
  • C - getpid() & getppid()
  • C - Rrules For Writing C/C++ Program
  • C - Tips For Embedded Development
  • C - Optimization Techniques
  • C Vs. Embedded C
  • C- File Management System Calls
  • C/C++ Multithreading
  • C/C++ - Sum of Array Using Multithreading

C Tips and Tricks

  • C - Copy Two Bytes Int. to Byte Buffer
  • C - Is Pre-increment Faster than Post-increment?
  • C - Create Delay Function
  • Why should We use 'f' With Float Literal in C?
  • C - Replacing a Part of String
  • C- Comparing Number of Characters of Two Strings
  • C - Safest Way to Check Value Using ==
  • C- Check EVEN or ODD W/O % Operator
  • C- Use Single Byte to Store 8 Values
  • C- Funny Trick to Use C++ in C
  • C - Trick to Print Maximum Value of an unsigned int
  • C - Print Maximum Value of an unsigned int using One's Compliment (~) Operator in C
  • Why we should use switch instead of if else?
  • How to initialize array elements with hexadecimal values in C?
  • How should we declare/define a pointer variable?

C Important Topics

  • C - Working With Hexadecimal
  • C - Working With octal
  • C - Convert ASCII String (char[]) to BYTE Array
  • C - Convert ASCII String (char[]) to Octal String
  • C - Convert ASCII String (char[]) to Hex String
  • C - Assign Binary Calue in a Variable Directly
  • C - Check Particular Bit is SET or Not
  • C- Set, Clear, & Toggle a Bit
  • C - Value of 'EOF'
  • C - Print printf("Hello world."); Using printf()
  • C - Print Text in New Line w/O Using '\n'
  • C - Return 0 From int main()
  • 'Super Loop' Architecture for Embedded C
  • C - Executing System Commands
  • C - Infix To Postfix Conversion Using Stack
  • C - Evaluation of Postfix Expressions Using Stack
  • C - Polynomial Addition Using Structure
  • C - conio.h Functions
  • SQLite with C language
  • C - SQL Table Creation, Insertion
  • C - Aptitude Questions
  • C - Interview Questions
  • C - Find Output Programs

Home » C programming language

How expression a=b=c (Multiple Assignment) evaluates in C programming?

Since C language does not support chaining assignment like a=b=c ; each assignment operator ( = ) operates on two operands only. Then how expression a=b=c evaluates?

According to operators associativity assignment operator ( = ) operates from right to left, that means associativity of assignment operator ( = ) is right to left.

Expression a=b=c is actually a=(b=c) , see how expression a=(b=c) evaluates?

  • Value of variable c will be assigned into variable b first.
  • Then value of variable b will be assigned into variable a .

Finally value of variables a and b will be same as the value of variable c .

Consider the following program

Assigning a value to multiple variables of same type

By using such kind of expression we can easily assign a value to multiple variables of same data type, for example - if we want to assign 0 to integer variables a , b , c and d ; we can do it by following expression:

Related Tutorials

  • Precedence and associativity of Arithmetic Operators
  • Difference b/w operators and operands in C
  • Unary Operators in C with Examples
  • Equality Operators in C,C++
  • Logical AND (&&) operator with example
  • Logical OR (||) operator with example
  • Logical NOT (!) operator with example
  • Modulus on negative numbers in C language
  • How expression a==b==c (Multiple Comparison) evaluates in C programming?
  • Complex return statement using comma operator in c programming language
  • Explain comma operator with an example
  • Bitwise Operators and their working
  • Bitwise One's Compliment (Bitwise NOT Operator) in C
  • Modulus of two float or double numbers in C language
  • Switch Case Tutorial, Syntax, Examples and Rules in C language
  • Switch Statements (features, disadvantages and difference with if else)
  • Using range with switch case statement
  • 'goto' Statement in C language
  • Use of break and continue within the loop in c
  • Print numbers from 1 to N using goto statement
  • Looping Tutorial in C programming
  • Nested Loops in C programming language
  • How to use for loop as infinite loop in C?

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

CProgramming Tutorial

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

Assignment Operators in C

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

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

In addition, C has several augmented assignment operators.

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

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

Simple Assignment Operator (=)

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

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

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

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

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

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

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

Augmented Assignment Operators

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

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

Run the code and check its output −

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

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

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

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

C – Pointer to Pointer (Double Pointer)

Prerequisite: Pointers in C

The pointer to a pointer in C is used when we want to store the address of another pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers . We can use a pointer to a pointer to change the values of normal pointers or create a variable-sized 2-D array. A double pointer occupies the same amount of space in the memory stack as a normal pointer.

double pointer in c

Declaration of Pointer to a Pointer in C

Declaring Pointer to Pointer is similar to declaring a pointer in C. The difference is we have to place an additional ‘*’ before the name of the pointer.

The above diagram shows the memory representation of a pointer to a pointer. The first pointer ptr1 stores the address of the variable and the second pointer ptr2 stores the address of the first pointer.  

Example of Double Pointer in C

How Double Pointer Works?

how double pointer works in C

The working of the double-pointer can be explained using the above image:

  • The double pointer is declared using the syntax shown above.
  • After that, we store the address of another pointer as the value of this new double pointer.
  • Now, if we want to manipulate or dereference to any of its levels, we have to use Asterisk ( * ) operator the number of times down the level we want to go.

Size of Pointer to Pointer in C

In the C programming language, a double pointer behaves similarly to a normal pointer in C. So, the size of the double-pointer variable is always equal to the normal pointers. We can verify this using the below C Program.

Example 1: C Program to find the size of a pointer to a pointer.

Note: The output of the above code also depends on the type of machine which is being used. The size of a pointer is not fixed in the C programming language and it depends on other factors like CPU architecture and OS used. Usually, for a 64-bit Operating System, the size will be 8 bytes and for a 32-bit Operating system, the size will be 4 bytes.

Application of Double Pointers in C

Following are the main uses of pointer to pointers in C:

  • They are used in the dynamic memory allocation of multidimensional arrays.
  • They can be used to store multilevel data such as the text document paragraph, sentences, and word semantics.
  • They are used in data structures to directly manipulate the address of the nodes without copying.
  • They can be used as function arguments to manipulate the address stored in the local pointer.

Multilevel Pointers in C

Double Pointers are not the only multilevel pointers supported by the C language. What if we want to change the value of a double pointer?

In this case, we can use a triple pointer, which will be a pointer to a pointer to a pointer i.e, int ***t_ptr.

Syntax of Triple Pointer

Similarly, to change the value of a triple pointer we can use a pointer to a pointer to a pointer to a pointer (Four level Pointer). In other words, we can say that to change the value of a ” level – x ” variable we can use a ” level – x+1 ” pointer. And this concept can be extended further.

Note : We can use any level pointer in C. There is no restriction about it but it makes the program very complex and vulnerable to errors.

Must Read – Function Pointer in C

Similar Reads

Please login to comment....

  • Top Language Learning Apps in 2024
  • Top 20 Free VPN for iPhone in 2024: October Top Picks
  • How to Underline in Discord
  • How to Block Someone on Discord
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

C Functions

C structures, c reference, c operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

C divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example Try it
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Advertisement

Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0 , which means true ( 1 ) or false ( 0 ). These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

Comparison operators are used to compare two values.

Note: The return value of a comparison is either true ( 1 ) or false ( 0 ).

In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:

A list of all comparison operators:

Operator Name Example Description Try it
== Equal to x == y Returns 1 if the values are equal
!= Not equal x != y Returns 1 if the values are not equal
> Greater than x > y Returns 1 if the first value is greater than the second value
< Less than x < y Returns 1 if the first value is less than the second value
>= Greater than or equal to x >= y Returns 1 if the first value is greater than, or equal to, the second value
<= Less than or equal to x <= y Returns 1 if the first value is less than, or equal to, the second value

Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values, by combining multiple conditions:

Operator Name Example Description Try it
&&  AND x < 5 &&  x < 10 Returns 1 if both statements are true
||  OR x < 5 || x < 4 Returns 1 if one of the statements is true
! NOT !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1

C Exercises

Test yourself with exercises.

Fill in the blanks to multiply 10 with 5 , and print the result:

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

What is the difference/ advantage of doing double assignment?

Is there any advantage / is it a bad practice in Java to do the below

I saw it in one of my peers code and I was surprised why he would do double assignment?

Is this something that is same as x = 5 or if x = x= 5 makes a difference?

gnat's user avatar

  • 8 Did you actually see x = x = 5 , or was it more like x = y = 5 ? The second one makes sense, but the first one is just weird. –  Tacroy Commented Jul 16, 2013 at 17:54
  • 14 Wouldn't call it a bad practice, it has more of an insanity vibe to it. Consider moving your desk farther from his. –  ZJR Commented Jul 16, 2013 at 18:20
  • 3 Are you sure it's not a cut & paste error? There's an apparently not-so-famous (since I can't find a link) quote that says "when you see someone you respect deep in thought, chances are he's thinking about lunch". You should ask him about it. –  Dan Pichelman Commented Jul 16, 2013 at 18:26
  • 4 @rao: How you word the question can create a different tone. "Why did you write that? It doesn't make sense." would put the programmer on the defensive. However, asking for clarification about what the line does opens the door more gently. If the description does not make sense, then you should come out an discuss how each of you have different understands of what is being done and what should be done. Your job is to make the code better, programmers should not be offended when an actual bug is found in their code. –  unholysampler Commented Jul 16, 2013 at 18:26
  • 3 This one is simply a nonsense, period. –  Pavel Horal Commented Jul 16, 2013 at 19:18
Is there any advantage/ is it a bad practice to do the below x= x = 5

You haven't specified the language, but in most C-like languages the value of an assignment is the value being assigned. That is, the value of the expression x = 5 is 5 , and the expression you're asking about is essentially the same as doing:

There's no value in the extra assignment, so no reason to do it.

Now, what you do sometimes see is the assignment of two (or more) variables to some value at the same time, like this:

In this case, you're assigning 5 to y , and then assigning the value of that expression (again, 5) to x . This ensures that both x and y get the same value.

Another possibility is that one of the assignments was intended to be a comparison, with the result assigned to the variable being compared:

This isn't a double assignment, it's assignment of the boolean expression x == 5 to x . That is, if the value of x is 5 before the expression, x will get the value of true (some non-zero integer); if x is not 5, x will be set to false (i.e. 0).

Caleb's user avatar

  • The language I am referring is Java, thanks for the clarification. –  rao Commented Jul 16, 2013 at 17:59
  • 3 x = x == 5 works in C, but (thankfully!) not in Java :) –  Andres F. Commented Jul 16, 2013 at 18:30
  • 1 @AndresF. Agree, and since we now know that the OP is talking about Java, the last part of my answer really doesn't apply. –  Caleb Commented Jul 16, 2013 at 18:34

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java variables or ask your own question .

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • Masked self-attention: How LLMs learn relationships between tokens
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network

Hot Network Questions

  • If Voyager is still an active NASA spacecraft, does it have a flight director? Is that a part time job?
  • Tikz: On straight lines moving balls on a circle inside a regular polygon
  • Macro not working in newcommand, but plain text input works
  • Does a passenger jet detect excessive weight in the tail after it's just landed?
  • Help Identify ebike electrical C13-like socket
  • Why was Z moved to the end of the alphabet when Zeta was near the beginning?
  • Including specific points in Plot
  • Understanding the ADC full scale input compared to a the reference voltage level of ADC
  • Why does Voyager use consumable hydrazine instead of reaction wheels that only rotate when moving the spacecraft?
  • Does the Rogue's Evasion cost a reaction?
  • What exactly do I buy when I buy an index-following ETF?
  • Does this work for page turns in a busy violin part?
  • In John 3:16, what is the significance of Jesus' distinction between the terms 'world' and 'everyone who believes' within the context?
  • Writing dental notations
  • Do mathematicians care about the validity ("truth") of the axioms?
  • How to sub-align expressions and preserve equation numbering?
  • Does legislation on transgender healthcare affect medical researchers?
  • How to make a wall of unicode symbols useful?
  • Help. It's not compiling!
  • MathOperator gives weird spacing in compositions, products
  • I want a smooth orthogonalization process
  • The most common one (L)
  • Does copying files from one drive to another also copy previously deleted data from the drive one?
  • Is it ethical to edit grammar, spelling, and wording errors in survey questions after the survey has been administered, prior to publication?

c double assignment

c double assignment

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • Coding Practice
  • Activecode Exercises
  • Mixed Up Code Practice
  • 6.1 Multiple assignment
  • 6.2 Iteration
  • 6.3 The while statement
  • 6.5 Two-dimensional tables
  • 6.6 Encapsulation and generalization
  • 6.7 Functions
  • 6.8 More encapsulation
  • 6.9 Local variables
  • 6.10 More generalization
  • 6.11 Glossary
  • 6.12 Multiple Choice Exercises
  • 6.13 Mixed-Up Code Exercises
  • 6.14 Coding Practice
  • 6. Iteration" data-toggle="tooltip">
  • 6.2. Iteration' data-toggle="tooltip" >

Before you keep reading...

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

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

6.1. Multiple assignment ¶

I haven’t said much about it, but it is legal in C++ to make more than one assignment to the same variable. The effect of the second assignment is to replace the old value of the variable with a new value.

The active code below reassigns fred from 5 to 7 and prints both values out.

The output of this program is 57 , because the first time we print fred his value is 5, and the second time his value is 7.

The active code below reassigns fred from 5 to 7 without printing out the initial value.

However, if we do not print fred the first time, the output is only 7 because the value of fred is just 7 when it is printed.

This kind of multiple assignment is the reason I described variables as a container for values. When you assign a value to a variable, you change the contents of the container, as shown in the figure:

image

When there are multiple assignments to a variable, it is especially important to distinguish between an assignment statement and a statement of equality. Because C++ uses the = symbol for assignment, it is tempting to interpret a statement like a = b as a statement of equality. It is not!

An assignment statement uses a single = symbol. For example, x = 3 assigns the value of 3 to the variable x . On the other hand, an equality statement uses two = symbols. For example, x == 3 is a boolean that evaluates to true if x is equal to 3 and evaluates to false otherwise.

First of all, equality is commutative, and assignment is not. For example, in mathematics if \(a = 7\) then \(7 = a\) . But in C++ the statement a = 7; is legal, and 7 = a; is not.

Furthermore, in mathematics, a statement of equality is true for all time. If \(a = b\) now, then \(a\) will always equal \(b\) . In C++, an assignment statement can make two variables equal, but they don’t have to stay that way!

The third line changes the value of a but it does not change the value of b , and so they are no longer equal. In many programming languages an alternate symbol is used for assignment, such as <- or := , in order to avoid confusion.

Although multiple assignment is frequently useful, you should use it with caution. If the values of variables are changing constantly in different parts of the program, it can make the code difficult to read and debug.

  • Checking if a is equal to b
  • Assigning a to the value of b
  • Setting the value of a to 4

Q-4: What will print?

  • There are no spaces between the numbers.
  • Remember, in C++ spaces must be printed.
  • Carefully look at the values being assigned.

Q-5: What is the correct output?

  • Remember that printing a boolean results in either 0 or 1.
  • Is x equal to y?
  • x is equal to y, so the output is 1.
  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Multiple Assignment

  Multiple Assignment

c double assignment

No, that assigns a, b, and c to c+5.
Xerzi's way is better. Mines is a sloppy version to do that. Pretty sure it doesn't get easier than that but if anyone finds a better solution i'll be curious to see it.
elipses( count, ...) { (count<=0) { 0; } va_list arg_ptr; va_start(arg_ptr, count); sum=0; ( i=0; i<count; i++) sum += va_arg(arg_ptr, ); va_end(arg_ptr); sum; }

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.

Learn C practically and Get Certified .

Popular Tutorials

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

  • Getting Started with C
  • Your First C Program

C Fundamentals

C Variables, Constants and Literals

C Data Types

C Input Output (I/O)

  • C Programming Operators

C Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Check Whether a Character is an Alphabet or not
  • Find ASCII Value of a Character
  • Find the Size of int, float, double and char
  • C isalpha()

C Type Conversion

In C programming, we can convert the value of one data type ( int, float , double , etc.) to another. This process is known as type conversion . Let's see an example,

Here, we are assigning the double value 34.78 to the integer variable number. In this case, the double value is automatically converted to integer value 34 .

This type of conversion is known as implicit type conversion . In C, there are two types of type conversion:

  • Implicit Conversion
  • Explicit Conversion
  • Implicit Type Conversion In C

As mentioned earlier, in implicit type conversion, the value of one type is automatically converted to the value of another type. For example,

The above example has a double variable with a value 4150.12 . Notice that we have assigned the double value to an integer variable.

Here, the C compiler automatically converts the double value 4150.12 to integer value 4150 .

Since the conversion is happening automatically, this type of conversion is called implicit type conversion.

  • Example: Implicit Type Conversion

The code above has created a character variable alphabet with the value 'a' . Notice that we are assigning alphabet to an integer variable.

Here, the C compiler automatically converts the character 'a' to integer 97 . This is because, in C programming, characters are internally stored as integer values known as ASCII Values .

ASCII defines a set of characters for encoding text in computers. In ASCII code, the character 'a' has integer value 97 , that's why the character 'a' is automatically converted to integer 97 .

If you want to learn more about finding ASCII values, visit find ASCII value of characters in C .

  • Explicit Type Conversion In C

In explicit type conversion, we manually convert values of one data type to another type. For example,

We have created an integer variable named number with the value 35 in the above program. Notice the code,

  • (double) - represents the data type to which number is to be converted
  • number - value that is to be converted to double type
  • Example: Explicit Type Conversion

We have created a variable number with the value 97 in the code above. Notice that we are converting this integer to character.

  • (char) - explicitly converts number into character
  • number - value that is to be converted to char type
  • Data Loss In Type Conversion

In our earlier examples, when we converted a double type value to an integer type, the data after decimal was lost.

Here, the data 4150.12 is converted to 4150 . In this conversion, data after the decimal, .12 is lost.

This is because double is a larger data type ( 8 bytes ) than int ( 4 bytes ), and when we convert data from larger type to smaller, there will be data loss..

Similarly, there is a hierarchy of data types in C programming. Based on the hierarchy, if a higher data type is converted to lower type, data is lost, and if lower data type is converted to higher type, no data is lost.

Data is lost when converting from a higher data type to a lower data type

  • data loss - if long double type is converted to double type
  • no data loss - if char is converted to int

Table of Contents

  • Introduction

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

List of all Keywords in C Language

cppreference.com

Assignment operators.

(C11)
Miscellaneous
General
(C11)
(C99)

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

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

[ edit ] Simple assignment

The simple assignment operator expressions have the form

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

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

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

rhs and lhs must satisfy one of the following:

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

[ edit ] Notes

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

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

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

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

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

[ edit ] Compound assignment

The compound assignment operator expressions have the form

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

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

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

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

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

[ edit ] References

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

[ edit ] See Also

Operator precedence

Common operators

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

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

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

!a
a && b
a || b

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

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

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


_Alignof
(since C11)

[ edit ] See also

for Assignment operators
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 19 August 2022, at 09:36.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Athletics turn two in the 3rd

The Athletics turn a 6-4-3 double play in the top of the 3rd inning

  • Season 2024
  • More From This Game
  • Jacob Wilson
  • Tyler Soderstrom
  • Oakland Athletics
  • in-game highlight
  • double play

c double assignment

  • Pitch Type: Sinker
  • Pitch Speed: 93.0 mph
  • Spin Rate: 1996 rpm

c double assignment

  • Exit Velocity: 103.7 mph
  • Launch Angle: 1°
  • Hit Distance: 57 ft
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

How can I declare and define multiple variables in one line using C++?

How do I initialise all these variables to zero without declaring each variable on a new line?

Mateen Ulhaq's user avatar

  • 58 Careful with those one-line multi-variable declarations. It's easier than you think to declare an int pointer followed by a list of regular integers ( int* a, b, c; doesn't do what it looks like). –  Chris Eberle Commented Jul 27, 2011 at 1:16
  • 5 There are only three variables, dude, write =0 for each one in their definitions. And, if you really want many variables, then try an array: int a[10]={0} will initialize each a[i] to 0 for you. –  Stan Commented Jul 27, 2011 at 1:33
  • 1 The compiler shouldn't allow that construct if it's going to behave differently than what a reasonable programmer would expect it to do...imho –  cph2117 Commented Nov 3, 2016 at 22:36
  • 3 @cph2117 A reasonable programmer would think 'hmm, this syntax could mean a couple of different things depending on how the grammar binds things' , look up the Standard to find out which is true, and get on with it. –  underscore_d Commented May 26, 2017 at 22:51
  • 2 Stop doing this. It just makes code harder to read. The point of writing code in a high level language is to make it simple for a maintainer to read. –  Loki Astari Commented Jun 3, 2020 at 15:33

11 Answers 11

Chris Eberle's user avatar

  • 1 Hi, I wonder if this expression support all type like std::vector<float> etc or only the primary data type –  littlefish Commented May 18, 2021 at 10:40
  • 1 Does this work in C also? –  Mehdi Charife Commented Jan 19, 2023 at 11:51
  • 1 @littlefish Of course it supports all types. See syntax (1) and (6) here: en.cppreference.com/w/cpp/language/copy_initialization As the variable is defined in the line, it calls a constructor and not the assignment operator of the type. –  Sebastian Commented Feb 5 at 20:14

With the following declaration, only the last variable ( index ) is set to 0 :

Instead, the following sets all variables to 0 :

But personally, I find the following methods much more readable:

hookenz's user avatar

  • 8 Between the last two I decide based on whether the two values must really be the same type ( bool previousInputValue, presentInputValue; ) or if they just happen to be the same type now but don't really need to be ( uint8_t height, width; might turn into uint8_t height; uint16_t width; in the future and should have been uint8_t height; uint8_t width; to begin with). –  altendky Commented Jun 17, 2015 at 15:08
  • Because writing uint8_t height; uint16_t width; instead of uint8_t height, width; saves 10 characters in the future. :-) you can of course do it however you like. Just make sure you make it easily read. So the last form is the most explicit. –  hookenz Commented Aug 14, 2016 at 20:56
  • 2 The last form is certainly the most explicit at stating the type of each variable and making it clear that each one is initialized. That said, it is not explicit about whether or not column and row are expected to be the same type or not. Perhaps we would both prefer the explicitness of int presentValue = 0; typeof(presentValue) previousValue = presentValue; , but I believe that typeof() is a non-standard GCC extension. –  altendky Commented Aug 14, 2016 at 21:20
  • 1 @altendky: C++11 introduced decltype as a portable version of GNU C typeof . So decltype (width) height = 0; works, but requires more mental effort to read. –  Peter Cordes Commented Oct 10, 2022 at 15:41

As @Josh said, the correct answer is:

You'll need to watch out for the same thing with pointers. This:

Is equivalent to:

  • 56 I hate that pointer thing, it makes no sense. The asterisk is part of the type, so it should apply to all of them. Imagine if unsigned long x, y; declared x as unsigned long but y as just unsigned , aka unsigned int ! That's exactly the same! </rant> –  Cam Jackson Commented Jan 22, 2013 at 5:41
  • 11 It makes sense. "int *a, b, c;" –  Jeroen Commented Jul 26, 2013 at 15:10
  • 11 @JeroenBollen Well yeah, it makes sense if you write your pointer asterisks next to the variable name instead of the type, but that in itself doesn't make any sense. Like I said above, the asterisk is part of the type, not part of the name, so it should by grouped with the type! –  Cam Jackson Commented Oct 28, 2013 at 13:32
  • 18 As a side not, actually it makes sense the the * isn't necessarily part of the type, as the int *a means that *a represents an int value. –  mdenton8 Commented Jan 21, 2014 at 7:34
  • 4 The point has already been made but just to add to it void is essentially the lack of a type but you can still make pointers to it. Thus why void* a will compile and void *a, b, c won't. This rationalization works for me. –  Josh C Commented Oct 21, 2015 at 17:26

If you declare one variable/object per line not only does it solve this problem, but it makes the code clearer and prevents silly mistakes when declaring pointers.

To directly answer your question though, you have to initialize each variable to 0 explicitly. int a = 0, b = 0, c = 0; .

Mark B's user avatar

Note that this form will work with custom types too, especially when their constructors take more than one argument.

Michael Kristofik's user avatar

  • 6 and nowadays with uniform initialisation (pending C++17 fixing this for auto ...): int column { 0 } , row { 0 } , index { 0 } ; –  underscore_d Commented Jun 11, 2016 at 18:49

As of C++17, you can use Structured Bindings :

Olivia Stork's user avatar

  • Is there any way to initialize several variables in a class like that? Without using class constructor and initialization list. I tried to do it, but it seems of a class method it is not possible to use Structural Bindings. –  Puya Commented Aug 8, 2023 at 11:38
  • 1 @Puya Not in a class, no. For a class every var should be explicitly declared. –  ivaigult Commented Aug 9, 2023 at 10:49

I wouldn't recommend this, but if you're really into it being one line and only writing 0 once, you can also do this:

Levi Uzodike's user avatar

As others have mentioned, from C++17 onwards you can make use of structured bindings for multiple variable assignments.

Combining this with std::array and template argument deduction we can write a function that assigns a value to an arbitrary number of variables without repeating the type or value .

j b's user avatar

Possible approaches:

  • Initialize all local variables with zero.
  • Have an array, memset or {0} the array.
  • Make it global or static.
  • Put them in struct , and memset or have a constructor that would initialize them to zero.

Ajay's user avatar

  • #define COLUMN 0 #define ROW 1 #define INDEX 2 #define AR_SIZE 3 int Data[ AR_SIZE ]; // Just an idea. –  Ajay Commented Jul 28, 2011 at 1:44
  • Sorry, I meant, why did you include the line " Have an array, memset or {0} the array. " in your answer? –  Mateen Ulhaq Commented Jul 28, 2011 at 2:16
  • memset(Data, 0, sizeof(Data)); // If this can be packed logically. –  Ajay Commented Jul 28, 2011 at 2:19

Pointers and references have similar syntax.

Some examples for newbies like me:

starriet 주녕차's user avatar

When you declare a variable without initializing it, a random number from memory is selected and the variable is initialized to that value.

user3487742's user avatar

  • 10 not really. The compiler decides 'this variable will be at address xxx', whatever happened to be at address xxx will be the initial value unless its set to something explicitly (by initialize or assignment) –  pm100 Commented Apr 2, 2014 at 17:08
  • 6 @pm100 although better , and true for any trivial implementation that doesn't go out of its way to harass users... that's still oversimplifying ;-) as using an uninitialised variable is UB, so in theory anything can happen, including any code using that variable simply being stripped out of the program - which is especially likely when optimisation is in play. –  underscore_d Commented Jun 11, 2016 at 18:52
  • 1 the value of that variable would be whatever was at the address it got, i.e. junk. –  Pedro V. G. Commented Dec 11, 2018 at 5:58
  • 2 @PedroVernetti It doesn't matter what happened to be at said address before the new variable was declared and happened to get the same address. If the user declares the new variable without initialising it with a value, and then reads the variable before having assigned it a value, the program has undefined behaviour. That's infinitely worse than "random" and "junk" and just needs to be avoided. –  underscore_d Commented Jun 16, 2019 at 17:03
  • 1 What happens to uninitialized variables in C/C++? - it's UB in C++ to read an uninitialized variable, except in very limited cases: if it had type unsigned char and you're using it to assign or initialize another unsigned char ( en.cppreference.com/w/cpp/language/default_initialization ). Then it's just indeterminate, see Where do the values of uninitialized variables come from, in practice on real CPUs? –  Peter Cordes Commented Oct 10, 2022 at 16:02

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ or ask your own question .

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • Masked self-attention: How LLMs learn relationships between tokens
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Should low-scoring meta questions no longer be hidden on the Meta.SO home...
  • Announcing the new Staging Ground Reviewer Stats Widget
  • Feedback Requested: How do you use the tagged questions page?

Hot Network Questions

  • The most common one (L)
  • In John 8, why did the Jews call themselves "children of Abraham" not "children of Jacob" or something else?
  • How do you tell someone to offer something to everyone in a room by taking it physically to everyone in the room so everyone can have it?
  • Why can't I set max delay between pins for my FPGA?
  • How to use 心/胸を焦がす in a grammatical sense?
  • Why is my Lenovo ThinkPad running Ubuntu using the e1000e Ethernet driver?
  • White (king and 2 bishops) vs Black (king and 1 knight). White to play and mate in 2
  • When moving countries, what should you list as location in job application?
  • Script on "Create public links for approved assets automatically" documentation page does not compile
  • Is it actually really easy to state conjectures, which are open and on the first view really hard to prove?
  • Five Hundred Cigarettes
  • Azure SQL Database CLR functions are working
  • Help. It's not compiling!
  • Is it possible to know where the Sun is just by looking at the Moon?
  • Is there a fast/clever way to return a logical vector if elements of a vector are in at least one interval?
  • What cameos did Stan Lee have in the DC universe?
  • Does copying files from one drive to another also copy previously deleted data from the drive one?
  • Does the Rogue's Evasion cost a reaction?
  • What is the mechanical equivalent of an electronic AND gate?
  • FIFO capture using cat not working as intended?
  • Can we solve the Sorites paradox with probability?
  • What exactly do I buy when I buy an index-following ETF?
  • Has Azerbaijan signed a contract to purchase JF-17s from Pakistan?
  • Why was Z moved to the end of the alphabet when Zeta was near the beginning?

c double assignment

IMAGES

  1. C++ Double

    c double assignment

  2. Assignment Operators in C

    c double assignment

  3. How to use C# Double Variables

    c double assignment

  4. C++ Double

    c double assignment

  5. C ++ Double: Como o tipo de dados Double funciona em C ++

    c double assignment

  6. Double Data Type in C++

    c double assignment

VIDEO

  1. Double Pointer

  2. Assignment Operator in C Programming

  3. Augmented assignment operators in C

  4. Parametric equations 4

  5. Double Closing: Solving Real Estate Conflicts

  6. Assignment Operator in C Programming

COMMENTS

  1. c

    sample1 = 0; sample2 = 0; specially if you are initializing to a non-zero value. Because, the multiple assignment translates to: sample2 = 0; sample1 = sample2; So instead of 2 initializations you do only one and one copy. The speed up (if any) will be tiny but in embedded case every tiny bit counts!

  2. "Double" assignment

    5. It depends on the language. In highly-object-oriented languages, double assignment results in the same object being assigned to multiple variables, so changes in one variable are reflected in the other. $ python -c 'a = b = [] ; a.append(1) ; print b'. [1] answered Nov 13, 2010 at 11:16.

  3. C Float and Double

    Double is double precision IEEE 754 floating point that provides precision up to 15 decimal points. Memory Usage. Float uses 32 bits or 4 bytes of memory. Double uses 64 bits or 8 bytes of memory. Range. Float can store values varying from 3.4 x 10 -38 to 3.4 x 10 +38. The range of double is 1.7×10 -308 to 1.7×10 +308.

  4. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...

  5. How expression a=b=c (Multiple Assignment) evaluates in C programming?

    Modulus of two float or double numbers in C language; Switch Case Tutorial, Syntax, Examples and Rules in C language; Switch Statements (features, disadvantages and difference with if else) Using range with switch case statement 'goto' Statement in C language; Use of break and continue within the loop in c; Print numbers from 1 to N using goto ...

  6. Assignment Operators in C

    Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign the value of A + B to C. +=. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A. -=.

  7. C

    The pointer to a pointer in C is used when we want to store the address of another pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to change the values of normal ...

  8. C Operators

    Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are known as Boolean values, and you will learn more about them in the Booleans and If ...

  9. What is the difference/ advantage of doing double assignment?

    This isn't a double assignment, it's assignment of the boolean expression x == 5 to x. That is, if the value of x is 5 before the expression, x will get the value of true (some non-zero integer); if x is not 5, x will be set to false (i.e. 0). Share. Improve this answer. Follow

  10. 6.1. Multiple assignment

    Multiple assignment — How to Think Like a Computer Scientist - C++. 6.1. Multiple assignment ¶. I haven't said much about it, but it is legal in C++ to make more than one assignment to the same variable. The effect of the second assignment is to replace the old value of the variable with a new value. The active code below reassigns fred ...

  11. Operators in C

    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.

  12. Multiple Assignment

    Thanks! No, that assigns a, b, and c to c+5. try parenthesizing the "c+=5". No, that assigns a, b, and c to c+5. I did it that way because you were adding the same values to them (5) and they all started with the same values (10) That is starting to look more like a recursive operation than variable assignment.

  13. Implicit conversions

    Conversion as if by assignment. In the assignment operator, the value of the right-hand operand is converted to the unqualified type of the left-hand operand.; In scalar initialization, the value of the initializer expression is converted to the unqualified type of the object being initialized ; In a function-call expression, to a function that has a prototype, the value of each argument ...

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

  15. C data types

    Contents. C data types. In the C programming language, data types constitute the semantics and characteristics of storage of data elements. They are expressed in the language syntax in form of declarations for memory locations or variables. Data types also determine the types of operations or methods of processing of data elements.

  16. C Type Conversion (With Examples)

    printf("Integer Value: %d", number); return 0; } Output. Double Value: 4150.12 Integer Value: 4150. Here, the data 4150.12 is converted to 4150.In this conversion, data after the decimal, .12 is lost. This is because double is a larger data type (8 bytes) than int (4 bytes), and when we convert data from larger type to smaller, there will be data loss..

  17. Assignment operators

    Correct behavior. CWG 1527. C++11. 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.

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

  19. Double assignment of the same variable in one expression in C++11

    The evaluation of the (compound) assignment-expression E2 is done in the following steps: 1) The behavior of a += 1 is equivalent to a = a + 1 but a is only evaluated once (§5.17/7). After evaluating the subexpressions a and 1 (in an arbitrary order), an lvalue-to-rvalue conversion is applied to a in order to read the value stored in a.

  20. 3/8 in. 90 Degree Flex Double Bite Saddle Connector

    Insulated throats on all DOUBLE BITE connectors provide maximum wire protection; Additional sizes available; Product details; Resources and downloads; Product details. General. Catalog Number. 3201DB. Conduit Type. Flexible Metal Conduit. Connector Type. Saddle. EU RoHS Indicator. Contact Manufacturer. Fitting Type. Connectors.

  21. Athletics turn two in the 3rd

    The Athletics turn a 6-4-3 double play in the top of the 3rd inning. Season 2024; More From This Game; Jacob Wilson; Zack Gelof; Tyler Soderstrom; Oakland Athletics; highlight; in-game highlight; defense; double play; Pitching OAK. Ginn. R. Pitch Type: Sinker; Pitch Speed: 93.0 mph; Spin Rate: 1996 rpm; Batting TEX.

  22. How can I declare and define multiple variables in one line using C++

    Have an array, memset or {0} the array. Make it global or static. Put them in struct, and memset or have a constructor that would initialize them to zero. #define COLUMN 0 #define ROW 1 #define INDEX 2 #define AR_SIZE 3 int Data [AR_SIZE]; // Just an idea.