Initialization versus Assignment in C++

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

C++ 17 | New ways to Assign values to Variables

  • Assigning function to a variable in C++
  • Different Ways to Initialize a Variable in C++
  • Inline Variables in C++ 17
  • How to Store Vectors as Values in a Map?
  • Scope of Variables in C++
  • Can Global Variables be dangerous ?
  • Swap Two Numbers Without Third Variable in C++
  • How to Access Global Variable if there is a Local Variable with Same Name in C/ C++?
  • Assigning Values to Variables
  • Assigning values to variables in R programming - assign() Function
  • How to Set Variable to Cell Value in Excel VBA?
  • What are the default values of static variables in C?
  • How to use Variables in Python3?
  • Assigning multiple variables in one line in Python
  • Variables under the hood in Python
  • Different ways to declare variable as constant in C
  • C# | Types of Variables
  • How to print a variable name in C?
  • C | Variable Declaration and Scope | Question 2

C++ 17 introduced many new ways to declare a variable. Earlier assignment and declaration was done using “=”

But now 2 more ways are introduced in C++17 . They are:

       

Explanation In C++ 17, the variable can be declared by providing values through parenthesis too. The difference between constructor initialization and the old normal way of initialization is that it will always return last value in the parenthesis no matter what it’s magnitude or sign is.

For example,

The value stored in a would be 1.

       

Unlike Constructor initialization, this assigning method can only take one value in the braces. Providing multiple values would return a compile error.

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

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.

Why declare a variable in one line, and assign to it in the next?

I often see in C and C++ code the following convention:

I initially assumed that this was a habit left over from the days when you had to declare all local variables at the top of the scope. But I've learned not to dismiss so quickly the habits of veteran developers. So, is there a good reason for declaring in one line, and assigning afterwards?

Robert Harvey's user avatar

  • 15 +1 for "I've learned not to dismiss so quickly the habits of veteran developers." That's a wise lesson to learn. –  Wildcard Commented Nov 30, 2015 at 15:56

7 Answers 7

In C89 all declarations had to be be at the beginning of a scope ( { ... } ), but this requirement was dropped quickly (first with compiler extensions and later with the standard).

These examples are not the same. some_type val = something; calls the copy constructor while val = something; calls the default constructor and then the operator= function. This difference is often critical.

Some people prefer to first declare variables and later define them, in the case they are reformatting their code later with the declarations in one spot and the definition in an other.

About the pointers, some people just have the habit to initialize every pointer to NULL or nullptr , no matter what they do with that pointer.

orlp's user avatar

  • 1 Great distinction for C++, thanks. What about in plain C? –  Jonathan Sterling Commented May 7, 2011 at 20:35
  • 13 The fact that MSVC still doesn't support declarations except at the beginning of a block when it's compiling in C mode is the source of endless irritation for me. –  Michael Burr Commented May 7, 2011 at 22:03
  • 5 @Michael Burr: This is because MSVC doesn't support C99 at all. –  orlp Commented May 7, 2011 at 22:05
  • 4 "some_type val = something; calls the copy constructor": it may call the copy constructor, but the Standard allows the compiler to elide the default-construction of a tempory, copy construction of val and destruction of the temporary and directly construct val using a some_type constructor taking something as sole argument. This is a very interesting and unusual edge case in C++... it means there's a presumption about the semantic meaning of these operations. –  Tony Commented May 9, 2011 at 9:15
  • 2 @Aerovistae: for built-in types they are the same, but the same can not always be said for user-defined types. –  orlp Commented Oct 11, 2012 at 18:48

You have tagged your question C and C++ at the same time, while the answer is significantly different in these languages.

Firstly, the wording of the title of your question is incorrect (or, more precisely, irrelevant to the question itself). In both of your examples the variable is declared and defined simultaneously, in one line. The difference between your examples is that in the first one the variables are either left uninitialized or initialized with a dummy value and then it is assigned a meaningful value later. In the second example the variables are initialized right away.

Secondly, in C++ language, as @nightcracker noted in his answer these two constructs are semantically different. The first one relies on initialization while the second one - on assignment. In C++ these operations are overloadable and therefore can potentially lead to different results (although one can note that producing non-equivalent overloads of initialization and assignment is not a good idea).

In the original standard C language (C89/90) it is illegal to declare variables in the middle of the block, which is why you might see variables declared uninitialized (or initialized with dummy values) at the beginning of the block and then assigned meaningful values later, when those meaningful values become available.

In C99 language it is OK to declare variables in the middle of the block (just like in C++), which means that the first approach is only needed in some specific situations when the initializer is not known at the point of declaration. (This applies to C++ as well).

AnT stands with Russia's user avatar

  • 2 @Jonathan Sterling: I read your examples. You probably need to brush up on the standard terminology of C and C++ languages. Specifically, on the terms declaration and definition , which have specific meanings in these languages. I'll repeat it again: in both of your examples the variables are declared and defined in one line. In C/C++ the line some_type val; immediately declares and defines the variable val . This is what I meant in my answer. –  AndreyT Commented May 7, 2011 at 20:53
  • 1 I see what you mean there. You're definitely right about declare and define being rather meaningless the way I used them. I hope you accept my apologies for the poor wording, and poorly-thought-out comment. –  Jonathan Sterling Commented May 7, 2011 at 20:55
  • 1 So, if the consensus is that “declare” is the wrong word, I'd suggest that someone with a better knowledge of the standard than me edit the Wikibooks page. –  Jonathan Sterling Commented May 7, 2011 at 21:11
  • 2 In any other context declare would be the right word, but since declare is a well-defined concept , with consequences, in C and C++ you can not use it as loosely as you could in other contexts. –  orlp Commented May 7, 2011 at 21:15
  • 2 @ybungalobill: You are wrong. Declaration and definition in C/C++ is not mutually exclusive concepts. Actually, definition is just a specific form of declaration . Every definition is a declaration at the same time (with few exceptions). There are defining declarations (i.e. definitions) and non-defining declarations. Moreover, normally the therm declaration is used all the time (even if it is a definition), except for the contexts when the distinction between the two is critical. –  AndreyT Commented May 7, 2011 at 21:52

I think it's an old habit, leftover from "local declaration" times. And therefore as answer to your question: No I don't think there's a good reason. I never do it myself.

I said something about that in my answer to a question by Helium3 .

Basically, I say it's a visual aid to easily see what is changed.

Community's user avatar

The other answers are pretty good. There's some history around this in C. In C++ there's the difference between a constructor and an assignment operator.

I'm surprised no one mentions the additional point: keeping declarations separate from use of a variable can sometimes be a lot more readable.

Visually speaking, when reading code, the more mundane artifacts, such as the types and names of variables, are not what jump out at you. It's the statements that you're usually most interested in, spend most time staring at, and so there's a tendency to glance over the rest.

If I have some types, names, and assignment all going on in the same tight space, it's a bit of information overload. Further, it means that something important is going on in the space that I usually glance over.

It may seem a bit counter-intuitive to say, but this is one instance where making your source take up more vertical space can make it better. I see this as akin to why you shouldn't write jam-packed lines which do crazy amounts of pointer arithmetic and assignment in a tight vertical space -- just because the language lets you get away with such things doesn't mean you should do it all the time. :-)

asveikau's user avatar

In C, this was the standard practice because variables had to be declared at the start of the function, unlike in C++, where it could be declared anywhere in the function body to be used thereafter. Pointers were set to 0 or NULL, because it just made sure that the pointer pointed to no garbage. Otherwise, there's no significant advantage that I can think of, which compels anyone to do like that.

Vite Falcon's user avatar

Pros for localising variable definitions and their meaningful initialisation:

if variables are habitually assigned a meaningful value when they first appear in the code (another perspective on the same thing: you delay their appearance until a meaningful value is avaialable) then there's no chance of them accidentally being used with a meaningless or uninitialised value (which can easily happen is some initialisation is accidentally bypassed due to conditional statements, short-circuit evaluation, exceptions etc.)

can be more efficient

  • avoids overheads of setting initial value (default construction or initialisation to some sentinel value like NULL)
  • operator= can sometimes be less efficient and require a temporary object
  • sometimes (esp. for inline functions) the optimiser can remove some/all inefficiencies

minimising the scope of variables in turn minimises average number of variables concurrently in scope : this

  • makes it easier to mentally track the variables in scope, the execution flows and statements that might affect those variables, and the import of their value
  • at least for some complex and opaque objects, this reduces resource usage (heap, threads, shared memory, descriptors) of the program

sometimes more concise as you're not repeating the variable name in a definition then in an initial meaningful assignment

necessary for certain types such as references and when you want the object to be const

Arguments for grouping variable definitions:

sometimes it's convenient and/or concise to factor out the type of a number of variables:

the_same_type v1, v2, v3;

(if the reason is just that the type name is overly long or complex, a typedef can sometimes be better)

sometimes it's desirable to group variables independently of their usage to emphasise the set of variables (and types) involved in some operation:

type v1; type v2; type v3;

This emphasises the commonality of type and makes it a little easier to change them, while still sticking to a variable per line which facilitates copy-paste, // commenting etc..

As is often the case in programming, while there can be a clear empirical benefit to one practice in most situations, the other practice really can be overwhelmingly better in a few cases.

Tony's user avatar

  • I wish more languages would distinguish the case where code declares and sets the value of a variable which would never be written elsewhere, though new variables could use the same name [i.e. where behavior would be the same whether the later statements used the same variable or a different one], from those where code creates a variable that must be writable in multiple places. While both use cases will execute the same way, knowing when variables may change is very helpful when trying to track down bugs. –  supercat Commented Apr 28, 2014 at 22:50

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

  • Featured on Meta
  • Upcoming sign-up experiments related to tags

Hot Network Questions

  • What do we mean when we say the CMB has a temperature and how do we measure it?
  • Recurrence relation with a sum
  • TCP source port sharing
  • What changes the velocity perpendicular to radius in an elliptical orbit?
  • Is it possible to retract an acceptance for a full time lecturer position?
  • What happens when you target a dead creature with Scrying?
  • How can I print the result of a comparison that uses "=~"?
  • Progressive matrix of line drawings
  • How to increase the lower bound while solving a MILP model?
  • Motivation for automated variable selection in case of p>n
  • What is equilibrium economics
  • What are the approaches of protecting against partially initialized objects?
  • a not-so optimized, not-so simple brainfuck source-to-source compiler to assembly (fasm) written in python that automatically compile using fasm
  • What is the meaning of 仅仅 in 仅仅复印、整理和把这些资料输入电脑就用了8年?
  • About Friedrichs historical contribution to QFT cited in Reed and Simon
  • I will not raise my voice to him ever again
  • How does the June 2024 Ukraine peace summit hope to achieve peace, if Russia is not invited?
  • Word for a country declaring independence from an empire
  • Is it known that the the sequence 7n+1 would diverge starting with 7?
  • Ubuntu Terminal with alternating colours for each line
  • How much of an advantage is it to have high acceleration in space combat
  • Three Wind Quartets (Gambaro) -- notes lengths don't add up (3.75 beats in common time)
  • How to explain Hazard Ratio in layperson's terms
  • I'm sorry to say... I'm allergic to retrocomputing. Any advice on sanitizing new acquisitions?

use assignment or value initialization

Learn Loner

We Make Learning Smoother.

Assignment and Initialization

Assignment and initialization are fundamental concepts in programming languages that involve storing values in variables. While they may seem similar, they serve different purposes and have distinct roles in programming.

Assignment:

Assignment is the process of giving a value to a variable. It involves storing a specific value or the result of an expression in a named memory location, which is the variable. The assignment operator, usually represented by the equal sign (=), is used to perform this operation.

Example in Python:

Assignment and Initialization

In this example, the value 10 is assigned to the variable ‘x’. After the assignment, ‘x’ holds the value 10.

Assignment is a common operation used to update the value of variables during program execution. It allows variables to store and represent changing data, making programs more dynamic and versatile.

Initialization:

Initialization is the process of setting a variable to a known value when it is first created. It ensures that the variable has a valid and predictable starting value before any further operations are performed on it.

Example in C++:

Assignment and initialization

In this example, the variable ‘count’ is initialized to 0 when it is declared. This ensures that the variable has a specific starting value before any other operations use it.

Initialization is essential for avoiding unpredictable behavior and bugs caused by using variables with undefined values. Many programming languages enforce initialization of variables to prevent potential issues and improve code reliability.

Differences and Use Cases:

The key difference between assignment and initialization lies in their timing and purpose:

  • Assignment occurs after a variable is declared and provides a value to an existing variable.
  • Initialization happens at the time of variable declaration and sets a starting value for the variable.
  • Assignment: Assigning new values to variables during program execution, updating data as it changes, and performing calculations using variable values.
  • Initialization: Setting variables to predefined starting values, ensuring variables are valid before use, and initializing data structures to default values.

Combination of Assignment and Initialization:

In many cases, assignment and initialization are combined when declaring variables. The variable is declared and assigned an initial value in a single statement.

Example in Java:

Assignment and Initialization

In this example, the variable ‘age’ is both declared and initialized with the value 25.

Importance and Best Practices:

Proper assignment and initialization of variables are critical for writing bug-free and maintainable code. Uninitialized variables can lead to undefined behavior and unexpected results, while incorrect assignments can produce incorrect calculations or data processing.

To ensure code reliability and readability, developers should:

  • Initialize variables at the time of declaration, whenever possible, to avoid using variables with undefined values.
  • Double-check assignment statements to ensure that the correct value is being assigned to the appropriate variable.
  • Use meaningful variable names to improve code understanding and maintainability.
  • Avoid reusing variables for different purposes to reduce confusion and potential bugs.

Numeric Data Types

Assignment and initialization of numeric data types involve storing numerical values in variables. Assignment is the process of assigning a specific value to a variable after its declaration, allowing the variable to hold and represent changing numerical data during program execution. Initialization, on the other hand, sets a starting value for the variable at the time of declaration, ensuring it has a valid value before any further operations. Numeric data types, such as integers and floating-point numbers, are commonly used for arithmetic calculations and numerical processing in programming. Proper assignment and initialization of numeric data types are essential for accurate calculations and data manipulation in programs.

Enumerations

Assignment and initialization of enumerations involve defining and setting values for user-defined data types that represent a set of named constant values. Enumerations are typically used to improve code readability and maintainability by providing meaningful names for specific values. Assignment in enumerations assigns specific constant values to the defined identifiers, allowing them to be used throughout the program. Initialization of enumerations is often done implicitly when the program starts, ensuring that the enumeration is ready for use. Enumerations are powerful tools for organizing related constants and simplifying code, making them an important aspect of many programming languages.

Assignment and initialization of Booleans involve working with a data type that represents logical values, typically denoted as “true” or “false.” Assignment assigns a Boolean value to a variable after its declaration, allowing the variable to hold and represent changing truth values during program execution. Initialization, on the other hand, sets a starting Boolean value for the variable at the time of declaration, ensuring it has a valid truth value before any further operations. Booleans are fundamental in decision-making, conditionals, and control flow in programming. Proper assignment and initialization of Booleans are crucial for implementing logic-based algorithms and ensuring the accuracy of conditional statements in programs.

Assignment and initialization of characters involve working with a data type that represents individual symbols from the character set, such as letters, digits, and special symbols. Assignment assigns a specific character to a variable after its declaration, allowing the variable to hold and represent changing characters during program execution. Initialization, on the other hand, sets a starting character value for the variable at the time of declaration, ensuring it has a valid character value before any further operations. Characters are commonly used for text processing, input/output operations, and string manipulation in programming. Proper assignment and initialization of characters are essential for handling textual data accurately and effectively in programs.

more related content on  Principles of Programming Languages

This browser is no longer supported.

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

Initializers

  • 6 contributors

An initializer specifies the initial value of a variable. You can initialize variables in these contexts:

In the definition of a variable:

As one of the parameters of a function:

As the return value of a function:

Initializers may take these forms:

An expression (or a comma-separated list of expressions) in parentheses:

An equals sign followed by an expression:

A braced initializer list. The list may be empty or may consist of a set of lists, as in the following example:

Kinds of initialization

There are several kinds of initialization, which may occur at different points in program execution. Different kinds of initialization aren't mutually exclusive—for example, list initialization can trigger value initialization and in other circumstances, it can trigger aggregate initialization.

Zero initialization

Zero initialization is the setting of a variable to a zero value implicitly converted to the type:

Numeric variables are initialized to 0 (or 0.0, or 0.0000000000, etc.).

Char variables are initialized to '\0' .

Pointers are initialized to nullptr .

Arrays, POD classes, structs, and unions have their members initialized to a zero value.

Zero initialization is performed at different times:

At program startup, for all named variables that have static duration. These variables may later be initialized again.

During value initialization, for scalar types and POD class types that are initialized by using empty braces.

For arrays that have only a subset of their members initialized.

Here are some examples of zero initialization:

Default initialization

Default initialization for classes, structs, and unions is initialization with a default constructor. The default constructor can be called with no initialization expression or with the new keyword:

If the class, struct, or union doesn't have a default constructor, the compiler emits an error.

Scalar variables are default initialized when they're defined with no initialization expression. They have indeterminate values.

Arrays are default initialized when they're defined with no initialization expression. When an array is default-initialized, its members are default initialized and have indeterminate values, as in the following example:

If the array members don't have a default constructor, the compiler emits an error.

Default initialization of constant variables

Constant variables must be declared together with an initializer. If they're scalar types they cause a compiler error, and if they're class types that have a default constructor they cause a warning:

Default initialization of static variables

Static variables that are declared with no initializer are initialized to 0 (implicitly converted to the type).

For more information about initialization of global static objects, see main function and command-line arguments .

Value initialization

Value initialization occurs in the following cases:

a named value is initialized using empty brace initialization

an anonymous temporary object is initialized using empty parentheses or braces

an object is initialized with the new keyword plus empty parentheses or braces

Value initialization does the following:

for classes with at least one public constructor, the default constructor is called

for nonunion classes with no declared constructors, the object is zero-initialized and the default constructor is called

for arrays, every element is value-initialized

in all other cases, the variable is zero initialized

Copy initialization

Copy initialization is the initialization of one object using a different object. It occurs in the following cases:

a variable is initialized using an equals sign

an argument is passed to a function

an object is returned from a function

an exception is thrown or caught

a non-static data member is initialized using an equals sign

class, struct, and union members are initialized by copy initialization during aggregate initialization. See Aggregate initialization for examples.

The following code shows several examples of copy initialization:

Copy initialization can't invoke explicit constructors.

In some cases, if the copy constructor of the class is deleted or inaccessible, copy initialization causes a compiler error.

Direct initialization

Direct initialization is initialization using (non-empty) braces or parentheses. Unlike copy initialization, it can invoke explicit constructors. It occurs in the following cases:

a variable is initialized with non-empty braces or parentheses

a variable is initialized with the new keyword plus non-empty braces or parentheses

a variable is initialized with static_cast

in a constructor, base classes and non-static members are initialized with an initializer list

in the copy of a captured variable inside a lambda expression

The following code shows some examples of direct initialization:

List initialization

List initialization occurs when a variable is initialized using a braced initializer list. Braced initializer lists can be used in the following cases:

a variable is initialized

a class is initialized with the new keyword

an argument passed to a function

one of the arguments in a direct initialization

in a non-static data member initializer

in a constructor initializer list

The following code shows some examples of list initialization:

Aggregate initialization

Aggregate initialization is a form of list initialization for arrays or class types (often structs or unions) that have:

no private or protected members

no user-provided constructors, except for explicitly defaulted or deleted constructors

no base classes

no virtual member functions

Aggregate initializers consist of a braced initialization list, with or without an equals sign, as in the following example:

You should see the following output:

Array members that are declared but not explicitly initialized during aggregate initialization are zero-initialized, as in myArr3 above.

Initializing unions and structs

If a union doesn't have a constructor, you can initialize it with a single value (or with another instance of a union). The value is used to initialize the first non-static field. This is different from struct initialization, in which the first value in the initializer is used to initialize the first field, the second to initialize the second field, and so on. Compare the initialization of unions and structs in the following example:

Initializing aggregates that contain aggregates

Aggregate types can contain other aggregate types, for example arrays of arrays, arrays of structs, and so on. These types are initialized by using nested sets of braces, for example:

Reference initialization

Variables of reference type must be initialized with an object of the type from which the reference type is derived, or with an object of a type that can be converted to the type from which the reference type is derived. For example:

The only way to initialize a reference with a temporary object is to initialize a constant temporary object. Once initialized, a reference-type variable always points to the same object; it can't be modified to point to another object.

Although the syntax can be the same, initialization of reference-type variables and assignment to reference-type variables are semantically different. In the preceding example, the assignments that change iVar and lVar look similar to the initializations, but have different effects. The initialization specifies the object to which the reference-type variable points; the assignment assigns to the referred-to object through the reference.

Because both passing an argument of reference type to a function and returning a value of reference type from a function are initializations, the formal arguments to a function are initialized correctly, as are the references returned.

Reference-type variables can be declared without initializers only in the following:

Function declarations (prototypes). For example:

Function-return type declarations. For example:

Declaration of a reference-type class member. For example:

Declaration of a variable explicitly specified as extern . For example:

When initializing a reference-type variable, the compiler uses the decision graph shown in the following figure to select between creating a reference to an object or creating a temporary object to which the reference points:

The decision graph begins with: is the initializer an lvalue of the same type or a type derived from the type of reference? If yes, the reference refers to the object specified in the initializer. If no, the next decision is whether the reference-type variable is a const T reference being initialized and can the initializer be implicitly converted to a T? If yes, the temporary is created and the reference variable becomes a name for that temporary. If no, it's an error.

Decision graph for initialization of reference types

References to volatile types (declared as volatile typename & identifier ) can be initialized with volatile objects of the same type or with objects that haven't been declared as volatile . They can't, however, be initialized with const objects of that type. Similarly, references to const types (declared as const typename & identifier ) can be initialized with const objects of the same type (or anything that has a conversion to that type or with objects that haven't been declared as const ). They can't, however, be initialized with volatile objects of that type.

References that aren't qualified with either the const or volatile keyword can be initialized only with objects declared as neither const nor volatile .

Initialization of external variables

Declarations of automatic, static, and external variables can contain initializers. However, declarations of external variables can contain initializers only if the variables aren't declared as extern .

Was this page helpful?

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

Submit and view feedback for

Additional resources

1.6 — Uninitialized variables and undefined behavior

Undefined behavior is like a box of chocolates. You never know what you’re going to get!

Implementation-defined behavior means the behavior of some syntax is left up to the implementation (the compiler) to define. Such behaviors must be consistent and documented, but different compilers may produce different results.

Differences Between Definition, Declaration, and Initialization

Last updated: March 18, 2024

use assignment or value initialization

  • Programming
  • Compilers and Linkers

1. Introduction

In this tutorial, we’ll explain the differences between definition, declaration, and initialization in computer programming.

The distinction between the three concepts isn’t clear in all languages. It depends on the language we’re coding in and the thing we want to declare, define or initialize.

2. Declarations

A declaration introduces a new identifier into a program’s namespace. The identifier can refer to a variable, a function, a type , a class, or any other construct the language at hand allows.

For a statement to be a declaration, it only needs to tell us what the declared identifier is. After reading a declaration statement, the code processor ( compiler or interpreter ) can differentiate between legal and illegal uses of the identifier.

For example, in C, we can declare a function by specifying its signature or a variable by specifying its type:

We see that g is a function with an integer argument and no return value. Similarly, x is an integer variable. That’s everything a compiler needs to know about g and x to report incorrect use. For instance, x(g) would raise a compiler error, whereas g(x) wouldn’t.

Other languages work the same. Their syntax rules may differ, but none allows us to use an identifier before declaring it.

2.1. Formal Languages

2.2. what declarations can’t do.

A declaration tells us what an identifier is. That isn’t enough.

Let’s go back to the above example. We can say that our C compiler wouldn’t complain about statements such as g(5) . However, g doesn’t have a body specifying the operations it applies to its argument. As a result, we can’t execute any statement involving g , so we’ll get a runtime error if we try.

In other words, declaring an identifier doesn’t guarantee its existence during the runtime. It’s our job to make sure that’s the case by defining it.

3. Definitions

When defining an identifier, we instruct the code processor to allocate , i.e., reserve a sufficiently large memory chunk for it. That means and requires different things depending on the identifier’s type.

For example, to define a function, we need to write its body. When handling the function’s definition, the processor converts it into machine code , places it in the reserved space, and links the function’s name to the place in memory containing the code. Without the body, the processor can’t know how much space to reserve.

To define a class in an object-oriented language , we implement its methods and specify its attributes. Similar goes for any type in any language.

To define a variable in a statically typed language , we need to specify its type explicitly. However, that’s the same as declaring it. So, a statement can both declare and define an identifier in some cases.

For instance, int x from the above example creates an identifier named x , reserves the space for an integer in the memory, and links the identifier to it:

Defining a variable

Consequently, the linker knows where to find the value of x . But that doesn’t mean the variable will have any value when we try to use it. Further, how do we define variables in dynamically typed languages?

We solve those issues with initialization.

4. Initialization

To initialize a variable, we assign it its starting value. That way, we make sure the expressions using the variable won’t throw a runtime error.

In a statically typed language, initialization and definition can be separate steps but can happen at the same time. For example:

In dynamically typed languages, we define a variable by initializing it since there are no explicit type declarations:

Further, depending on the language rules or the code processor, each type can have a default value . That means that every variable in such a statically typed language will get its type’s default value when we define it. If that’s the case, initialization is implicit.

5. Conclusion

In this article, we talked about declarations, definitions, and initialization. They mean different things but sometimes overlap in code.

cppreference.com

Direct-initialization.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block

    

/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)      

expression
pointer
specifier

specifier (C++11)    
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
(C++11)
(C++11)

Initializes an object from explicit set of constructor arguments.

Syntax Explanation Notes Example See also

[ edit ] Syntax

T object arg

T object arg1, arg2, ...

(1)
T object arg (2) (since C++11)
T other

T arg1, arg2, ...

(3)
T other (4)
T args, ... (5)
Class Class member args, ... ... (6)
arg ... (7) (since C++11)

[ edit ] Explanation

Direct-initialization is performed in the following situations:

The effects of direct-initialization are:

  • If T is an array type,
(until C++20)
, except that narrowing conversions are allowed and any elements without an initializer are . A { explicit A(int i = 0) {} };   A a[2](A(1)); // OK: initializes a[0] with A(1) and a[1] with A() A b[2]{A(1)}; // error: implicit copy-list-initialization of b[1] // from {} selected explicit constructor (since C++20)
  • If T is a class type,
expression whose type is the same class as (ignoring cv-qualification), the initializer expression itself, rather than a temporary materialized from it, is used to initialize the destination object.
(Before C++17, the compiler may elide the construction from the prvalue temporary in this case, but the appropriate constructor must still be accessible: see )
(since C++17)
  • the constructors of T are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.
except that narrowing conversions are permitted, designated initializers are not allowed, a temporary bound to a reference does not have its lifetime extended, there is no brace elision, and any elements without an initializer are . B { int a; int&& r; };   int f(); int n = 10;   B b1{1, f()}; // OK, lifetime is extended B b2(1, f()); // well-formed, but dangling reference B b3{1.0, 1}; // error: narrowing conversion B b4(1.0, 1); // well-formed, but dangling reference B b5(1.0, std::move(n)); // OK (since C++20)
  • Otherwise, if T is a non-class type but the source type is a class type, the conversion functions of the source type and its base classes, if any, are examined and the best match is selected by overload resolution. The selected user-defined conversion is then used to convert the initializer expression into the object being initialized.
  • Otherwise, if T is bool and the source type is std::nullptr_t , the value of the initialized object is false .
  • Otherwise, standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T , and the initial value of the object being initialized is the (possibly converted) value.

[ edit ] Notes

Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non- explicit constructors and non-explicit user-defined conversion functions , while direct-initialization considers all constructors and all user-defined conversion functions.

In case of ambiguity between a variable declaration using the direct-initialization syntax (1) (with round parentheses) and a function declaration , the compiler always chooses function declaration. This disambiguation rule is sometimes counter-intuitive and has been called the most vexing parse .

[ edit ] Example

[ edit ] see also.

  • copy elision
  • converting constructor
  • copy assignment
  • copy constructor
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • initializer list
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • 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 1 September 2023, at 06:05.
  • This page has been accessed 331,797 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Get the Reddit app

a subreddit for c++ questions and answers

"clearing an object of non-trivial type; use assignment or value-initialization instead"

First, I barely know any C/C++ but only Java. Anyhow, I'm trying to compile touchpad drivers for my Chromebook (running Debian).

Here's the error message I get after running make :

Here's mouse_interpreter.cc and the rest of the files.

And gcc --version

gcc (Debian 9.2.1-8) 9.2.1 20190909

Now, it does successfully compile after I delete the -Werror flag in Makefile. If all warnings are suppressed, and the code compiles successfully, does that mean we're all good?

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG warning: 'void* memset(void*, int, size_t)' clearing an object of non-trivial type 'class SdFile'; use assignment or value-initialization instead [-Wclass-memaccess] #24274

@victoroos

victoroos commented Jun 2, 2022

code?

Yes, and the problem still exists.

When compiling the code in visual studie for the LPC1768 platform I get error:

Now the printer isn't able to read the card even though it sees it being attached.

Any tips?
cheers
Vic

2.0.9.3

Tevo tarantula Pro

Cura

and . for maximum logging.) G-code.

@oliver-eifler

oliver-eifler commented Jun 2, 2022

You don't use latest bugfix as this 'issue' is already fixed since May 17, 2022
see
the ZERO macro is now
#define ZERO(a) memset((void*)a,0,sizeof(a))

and it's only a warning not an error - nothing which would disturb the function

try real latest bugfix - from today - and see if you still get the warning

Sorry, something went wrong.

@thisiskeithb

thisiskeithb commented Jun 2, 2022

Configs are way out of date which gives it away as well.

@thisiskeithb

Duplicate of

@github-actions

github-actions bot commented Aug 2, 2022

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions

No branches or pull requests

@oliver-eifler

IMAGES

  1. PPT

    use assignment or value initialization

  2. Difference Between Variable Declaration vs Assignment vs Initialization?

    use assignment or value initialization

  3. Declaration vs Initialization vs Invocation in Programming

    use assignment or value initialization

  4. PPT

    use assignment or value initialization

  5. Assignment And Initialization

    use assignment or value initialization

  6. Assignment And Initialization

    use assignment or value initialization

VIDEO

  1. Variable Declaration, Initialization, Assignment Lecture

  2. How to Use sync.OnceValue in Golang for Efficient Initialization

  3. Exploring Default Values in C#

  4. 9 C plus plus Variables , initialization and assignment

  5. AMT repair AMT oil leakge and gear swifting problem in maruti shuzuki wagnor #AGS #amt #amtrepair

  6. 15. Assignment Operators Example

COMMENTS

  1. 1.4

    1.4 — Variable assignment and initialization. Alex May 26, 2024. In the previous lesson ( 1.3 -- Introduction to objects and variables ), we covered how to define a variable that we can use to store values. In this lesson, we'll explore how to actually put values into variables and use those values. As a reminder, here's a short snippet ...

  2. What is the difference between initialization and assignment?

    To initialize is to make ready for use. And when we're talking about a variable, that means giving the variable a first, useful value. And one way to do that is by using an assignment. So it's pretty subtle: assignment is one way to do initialization. Assignment works well for initializing e.g. an int, but it doesn't work well for initializing ...

  3. Value-initialization

    The way to value-initialize a named variable before C++11 was T object = T();, which value-initializes a temporary and then copy-initializes the object: most compilers optimize out the copy in this case. References cannot be value-initialized. As described in functional cast, the syntax T()(1) is prohibited if T names an array type, while T{}(5 ...

  4. Initialization

    Initialization. Initialization of a variable provides its initial value at the time of construction. The initial value may be provided in the initializer section of a declarator or a new expression. It also takes place during function calls: function parameters and the function return values are also initialized.

  5. Initialization vs. Assignment[C++ class-defined objects]

    The first is assignment and the second is initialization, which can occur in three ways: When one object explicitly initializes another, such as in a declaration, When a copy of an object is made to be passed to a function, or. When a temporary object is generated (most commonly, as a return value). The copy constructor applies only to ...

  6. C++ 17

    C++ 17 introduced many new ways to declare a variable. Earlier assignment and declaration was done using "=". Example: int a = 5; But now 2 more ways are introduced in C++17. They are: Constructor initialization: In this way, the value of the variable is enclosed in parentheses ( () ). In this way, value can be passed in two ways shown below.

  7. Why declare a variable in one line, and assign to it in the next?

    The first one relies on initialization while the second one - on assignment. In C++ these operations are overloadable and therefore can potentially lead to different results (although one can note that producing non-equivalent overloads of initialization and assignment is not a good idea).

  8. Variables Initialization

    using an assignment statement; reading a value from keyboard or other device with a READ statement. The way of initializing a variable is very similar to the use of PARAMETER attribute. More precisely, do the following to initial a variable with the value of an expression: add an equal sign (=) to the right of a variable name

  9. Assignment and Initialization

    Assignment is the process of assigning a specific value to a variable after its declaration, allowing the variable to hold and represent changing numerical data during program execution. Initialization, on the other hand, sets a starting value for the variable at the time of declaration, ensuring it has a valid value before any further operations.

  10. memset() or value initialization to zero out a struct?

    102. In Win32 API programming it's typical to use C struct s with multiple fields. Usually only a couple of them have meaningful values and all others have to be zeroed out. This can be achieved in either of the two ways: STRUCT theStruct; memset( &theStruct, 0, sizeof( STRUCT ) ); or. STRUCT theStruct = {};

  11. Initializers

    An initializer specifies the initial value of a variable. You can initialize variables in these contexts: Point get_new_point(int x, int y) { return Point{ x, y }; } Initializers may take these forms: A braced initializer list. The list may be empty or may consist of a set of lists, as in the following example:

  12. 1.6

    In lesson 1.4 -- Variable assignment and initialization, we noted that when no initializer is provided, the variable is default-initialized. In most cases (such as this one), default-initialization performs no actual initialization. Thus we'd say x is uninitialized. We're focused on the outcome (the object has not been given a known value ...

  13. Differences Between Definition, Declaration, and Initialization

    It depends on the language we're coding in and the thing we want to declare, define or initialize. 2. Declarations. A declaration introduces a new identifier into a program's namespace. The identifier can refer to a variable, a function, a type, a class, or any other construct the language at hand allows. For a statement to be a declaration ...

  14. Direct-initialization

    Explanation. Direct-initialization is performed in the following situations: 1) Initialization with a nonempty parenthesized list of expressions or braced-init-lists(since C++11). 2) Initialization of an object of non-class type with a single brace-enclosed initializer (note: for class types and other uses of braced-init-list, see list ...

  15. Java: define terms initialization, declaration and assignment

    assignment: throwing away the old value of a variable and replacing it with a new one. initialization: it's a special kind of assignment: the first.Before initialization objects have null value and primitive types have default values such as 0 or false.Can be done in conjunction with declaration. declaration: a declaration states the type of a variable, along with its name.

  16. "clearing an object of non-trivial type; use assignment or value

    but what if there was a member that has side effect for the assignment operator. memset wouldn't execute the side effects. what if there was an enumeration for which zero is an illegal value. Reply reply

  17. error: clearing an object of non-trivial type; use assignment or value

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  18. [Compile] Some compile warning in gcc > 8 #5546

    Describe the bug clearing an object of type 'struct ' with no trivial copy-assignment; use assignment or value-initialization instead. class should convert to pod type: decimal12_t uint24_t doris::OLAPIndexFixedHeader. Expected behavior no warning here. Additional context Add any other context about the problem here.

  19. c++

    While both initialization and assignment give a variable a value, the two do not use the same code to do it. Further details: With C++11 and later, if there is a move constructor, copy initialization will use it instead, because the result of the conversion is a temporary.

  20. BUG warning: 'void* memset(void*, int, size_t)' clearing an ...

    Use saved searches to filter your results more quickly. Name. Query. To see all available qualifiers, see our documentation. ... size_t)' clearing an object of non-trivial type 'class SdFile'; use assignment or value-initialization instead [-Wclass-memaccess] #24274. Closed 1 of 4 tasks. victoroos opened this issue Jun 2, 2022 · 4 comments ...

  21. error clearing an object of non-trivial type with memset

    @Tobibobi I'd say the cases are few where I'd prefer a memset to that of assigning a default initialized object to the target. I'd be surprised if tmp = decltype(tmp){}; produced any less efficient code than memset and it would always be valid for types that can be default initialized. It's also future proof. If the default initialization is changed to something else, writing 0 straight into ...