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
- 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
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
- Pitch Type: Sinker
- Pitch Speed: 93.0 mph
- Spin Rate: 1996 rpm
- 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?
- 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
- 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:
- 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; .
Note that this form will work with custom types too, especially when their constructors take more than one argument.
- 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 :
- 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:
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 .
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.
- #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:
When you declare a variable without initializing it, a random number from memory is selected and the variable is initialized to that value.
- 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?
IMAGES
VIDEO
COMMENTS
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!
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.
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.
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 ...
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 ...
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. -=.
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 ...
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 ...
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
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 ...
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.
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.
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 ...
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:
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.
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..
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.
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 ...
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.
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.
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.
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.