Learn C++

1.4 — Variable assignment and initialization

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 that first allocates a single integer variable named x , then allocates two more integer variables named y and z :

Variable assignment

After a variable has been defined, you can give it a value (in a separate statement) using the = operator . This process is called assignment , and the = operator is called the assignment operator .

By default, assignment copies the value on the right-hand side of the = operator to the variable on the left-hand side of the operator. This is called copy assignment .

Here’s an example where we use assignment twice:

This prints:

When we assign value 7 to variable width , the value 5 that was there previously is overwritten. Normal variables can only hold one value at a time.

One of the most common mistakes that new programmers make is to confuse the assignment operator ( = ) with the equality operator ( == ). Assignment ( = ) is used to assign a value to a variable. Equality ( == ) is used to test whether two operands are equal in value.

Initialization

One downside of assignment is that it requires at least two statements: one to define the variable, and another to assign the value.

These two steps can be combined. When a variable is defined, you can also provide an initial value for the variable at the same time. This process is called initialization . The syntax used to initialize a variable is called an initializer .

Initialization in C++ is surprisingly complex, so we’ll present a simplified view here.

There are 6 basic ways to initialize variables in C++:

You may see the above forms written with different spacing (e.g. int d{7}; ). Whether you use extra spaces for readability or not is a matter of personal preference.

Default initialization

When no initializer is provided (such as for variable a above), this is called default initialization . In most cases, default initialization performs no initialization, and leaves a variable with an indeterminate value.

We’ll discuss this case further in lesson ( 1.6 -- Uninitialized variables and undefined behavior ).

Copy initialization

When an initial value is provided after an equals sign, this is called copy initialization . This form of initialization was inherited from C.

Much like copy assignment, this copies the value on the right-hand side of the equals into the variable being created on the left-hand side. In the above snippet, variable width will be initialized with value 5 .

Copy initialization had fallen out of favor in modern C++ due to being less efficient than other forms of initialization for some complex types. However, C++17 remedied the bulk of these issues, and copy initialization is now finding new advocates. You will also find it used in older code (especially code ported from C), or by developers who simply think it looks more natural and is easier to read.

For advanced readers

Copy initialization is also used whenever values are implicitly copied or converted, such as when passing arguments to a function by value, returning from a function by value, or catching exceptions by value.

Direct initialization

When an initial value is provided inside parenthesis, this is called direct initialization .

Direct initialization was initially introduced to allow for more efficient initialization of complex objects (those with class types, which we’ll cover in a future chapter). Just like copy initialization, direct initialization had fallen out of favor in modern C++, largely due to being superseded by list initialization. However, we now know that list initialization has a few quirks of its own, and so direct initialization is once again finding use in certain cases.

Direct initialization is also used when values are explicitly cast to another type.

One of the reasons direct initialization had fallen out of favor is because it makes it hard to differentiate variables from functions. For example:

List initialization

The modern way to initialize objects in C++ is to use a form of initialization that makes use of curly braces. This is called list initialization (or uniform initialization or brace initialization ).

List initialization comes in three forms:

As an aside…

Prior to the introduction of list initialization, some types of initialization required using copy initialization, and other types of initialization required using direct initialization. List initialization was introduced to provide a more consistent initialization syntax (which is why it is sometimes called “uniform initialization”) that works in most cases.

Additionally, list initialization provides a way to initialize objects with a list of values (which is why it is called “list initialization”). We show an example of this in lesson 16.2 -- Introduction to std::vector and list constructors .

List initialization has an added benefit: “narrowing conversions” in list initialization are ill-formed. This means that if you try to brace initialize a variable using a value that the variable can not safely hold, the compiler is required to produce a diagnostic (usually an error). For example:

In the above snippet, we’re trying to assign a number (4.5) that has a fractional part (the .5 part) to an integer variable (which can only hold numbers without fractional parts).

Copy and direct initialization would simply drop the fractional part, resulting in the initialization of value 4 into variable width . Your compiler may optionally warn you about this, since losing data is rarely desired. However, with list initialization, your compiler is required to generate a diagnostic in such cases.

Conversions that can be done without potential data loss are allowed.

To summarize, list initialization is generally preferred over the other initialization forms because it works in most cases, it disallows narrowing conversions, and it supports initialization with lists of values (something we’ll cover in a future lesson). While you are learning, we recommend sticking with list initialization (or value initialization).

Best practice

Prefer direct list initialization (or value initialization) for initializing your variables.

Author’s note

Bjarne Stroustrup (creator of C++) and Herb Sutter (C++ expert) also recommend using list initialization to initialize your variables.

In modern C++, there are some cases where list initialization does not work as expected. We cover one such case in lesson 16.2 -- Introduction to std::vector and list constructors .

Because of such quirks, some experienced developers now advocate for using a mix of copy, direct, and list initialization, depending on the circumstance. Once you are familiar enough with the language to understand the nuances of each initialization type and the reasoning behind such recommendations, you can evaluate on your own whether you find these arguments persuasive.

Value initialization and zero initialization

When a variable is initialized using empty braces, value initialization takes place. In most cases, value initialization will initialize the variable to zero (or empty, if that’s more appropriate for a given type). In such cases where zeroing occurs, this is called zero initialization .

Q: When should I initialize with { 0 } vs {}?

Use an explicit initialization value if you’re actually using that value.

Use value initialization if the value is temporary and will be replaced.

Initialize your variables

Initialize your variables upon creation. You may eventually find cases where you want to ignore this advice for a specific reason (e.g. a performance critical section of code that uses a lot of variables), and that’s okay, as long the choice is made deliberately.

Related content

For more discussion on this topic, Bjarne Stroustrup (creator of C++) and Herb Sutter (C++ expert) make this recommendation themselves here .

We explore what happens if you try to use a variable that doesn’t have a well-defined value in lesson 1.6 -- Uninitialized variables and undefined behavior .

Initialize your variables upon creation.

Initializing multiple variables

In the last section, we noted that it is possible to define multiple variables of the same type in a single statement by separating the names with a comma:

We also noted that best practice is to avoid this syntax altogether. However, since you may encounter other code that uses this style, it’s still useful to talk a little bit more about it, if for no other reason than to reinforce some of the reasons you should be avoiding it.

You can initialize multiple variables defined on the same line:

Unfortunately, there’s a common pitfall here that can occur when the programmer mistakenly tries to initialize both variables by using one initialization statement:

In the top statement, variable “a” will be left uninitialized, and the compiler may or may not complain. If it doesn’t, this is a great way to have your program intermittently crash or produce sporadic results. We’ll talk more about what happens if you use uninitialized variables shortly.

The best way to remember that this is wrong is to consider the case of direct initialization or brace initialization:

Because the parenthesis or braces are typically placed right next to the variable name, this makes it seem a little more clear that the value 5 is only being used to initialize variable b and d , not a or c .

Unused initialized variables warnings

Modern compilers will typically generate warnings if a variable is initialized but not used (since this is rarely desirable). And if “treat warnings as errors” is enabled, these warnings will be promoted to errors and cause the compilation to fail.

Consider the following innocent looking program:

When compiling this with the g++ compiler, the following error is generated:

and the program fails to compile.

There are a few easy ways to fix this.

  • If the variable really is unused, then the easiest option is to remove the defintion of x (or comment it out). After all, if it’s not used, then removing it won’t affect anything.
  • Another option is to simply use the variable somewhere:

But this requires some effort to write code that uses it, and has the downside of potentially changing your program’s behavior.

The [[maybe_unused]] attribute C++17

In some cases, neither of the above options are desirable. Consider the case where we have a bunch of math/physics values that we use in many different programs:

If we use these a lot, we probably have these saved somewhere and copy/paste/import them all together.

However, in any program where we don’t use all of these values, the compiler will complain about each variable that isn’t actually used. While we could go through and remove/comment out the unused ones for each program, this takes time and energy. And later if we need one that we’ve previously removed, we’ll have to go back and re-add it.

To address such cases, C++17 introduced the [[maybe_unused]] attribute, which allows us to tell the compiler that we’re okay with a variable being unused. The compiler will not generate unused variable warnings for such variables.

The following program should generate no warnings/errors:

Additionally, the compiler will likely optimize these variables out of the program, so they have no performance impact.

In future lessons, we’ll often define variables we don’t use again, in order to demonstrate certain concepts. Making use of [[maybe_unused]] allows us to do so without compilation warnings/errors.

Question #1

What is the difference between initialization and assignment?

Show Solution

Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a value at some point after the variable is created.

Question #2

What form of initialization should you prefer when you want to initialize a variable with a specific value?

Direct list initialization (aka. direct brace initialization).

Question #3

What are default initialization and value initialization? What is the behavior of each? Which should you prefer?

Default initialization is when a variable initialization has no initializer (e.g. int x; ). In most cases, the variable is left with an indeterminate value.

Value initialization is when a variable initialization has an empty brace (e.g. int x{}; ). In most cases this will perform zero-initialization.

You should prefer value initialization to default initialization.

guest

  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Explain the variable declaration, initialization and assignment in C language

The main purpose of variables is to store data in memory. Unlike constants, it will not change during the program execution. However, its value may be changed during execution.

The variable declaration indicates that the operating system is going to reserve a piece of memory with that variable name.

Variable declaration

The syntax for variable declaration is as follows −

For example,

Here, a, b, c, d are variables. The int, float, double are the data types.

Variable initialization

The syntax for variable initialization is as follows −

Variable Assignment

A variable assignment is a process of assigning a value to a variable.

Rules for defining variables

A variable may be alphabets, digits, and underscore.

A variable name can start with an alphabet, and an underscore but, can’t start with a digit.

Whitespace is not allowed in the variable name.

A variable name is not a reserved word or keyword. For example, int, goto etc.

Following is the C program for variable assignment −

 Live Demo

When the above program is executed, it produces the following result −

Bhanu Priya

Related Articles

  • Initialization, declaration and assignment terms in Java
  • Explain variable declaration and rules of variables in C language
  • Explain the concept of logical and assignment operator in C language
  • Variable initialization in C++
  • What is the difference between initialization and assignment of values in C#?
  • Structure declaration in C language
  • Explain the accessing of structure variable in C language
  • Explain scope of a variable in C language.
  • Explain Lifetime of a variable in C language.
  • Explain Binding of a variable in C language.
  • Initialization of variable sized arrays in C
  • MySQL temporary variable assignment?
  • Explain Compile time and Run time initialization in C programming?
  • Rules For Variable Declaration in Java
  • Explain the Difference Between Definition and Declaration

Kickstart Your Career

Get certified by completing the course

Maker's Aid Logo

Maker's Aid

Declare vs. Assign in JavaScript

What’s the difference between declaring a constant or variable and assigning it a value? Here’s everything you need to know.

variable declaration vs assignment

You’re just getting started with JavaScript, and you want to learn the difference between declaring a constant or variable and assigning (or initializing) it.

To declare a constant or variable is to give it an identifier so that you can reference it. To assign a value to a variable is to store information in it.

This beginner’s guide will teach you how to declare constants and variables, how to assign them values, and more.

In JavaScript, you can create constants and variables—basically, objects that hold information—and give them values that you can use later in your code.

You create a constant or variable by declaring it with a const , let , or var statement.

Declare a Constant

The const statement is for constants:

Constants cannot be redeclared or reassigned.

Declare a Variable With Let

The let statement is for variables with a block scope:

Variables declared with the let statement cannot be redeclared but can be reassigned.

Declare a Variable With Var

And the var statement is for variable with a function scope or global scope:

Variables declared with the var statement can be redeclared and reassigned.

Once you’ve declared a constant or variable, you can assign it a value with the assignment operator (=) .

The first time you assign a value to a constant or variable is called “assignment” or “initialization.”

You can initialize a constant or variable at declaration:

You can also declare your constant or variable empty, then initialize it post-declaration:

The Difference Between Declaring and Assigning

To declare a constant or a variable is to create a data object and give a name, so that you can reference it later in your code. To assign a constant or variable, on the other hand, is to give it a value.

Another name for declaration, if oversimplified, could be “naming it.” And another name for assignment could be “storing information in it.”

To Redeclare

In JavaScript, certain types of data objects can be declared more than once, or “redeclared.”

Constants cannot be redeclared within the same scope:

Neither can variables declared with the let statement:

However, variables declared with the var statement can be redeclared:

To Reassign

In JavaScript, certain types of data objects can be assigned values more than once, or “reassigned.”

Constants cannot be reassigned within the same scope:

Variables declared with let or var , on the other hand, can be reassigned within the same scope:

Whether it is a good idea to redeclare and reassign in your code is the subject of heated debate in the JavaScript development community.

Summing It Up

Thank you for reading this far and I hope this tutorial helped.

You now know the difference between declaring a constant or variable and assigning it a value. You also know when you can—and cannot—redeclare and reassign constants or variables depending on the type of statement that you used.

If you have any questions, be sure to leave a reply below.

Leave a comment Cancel reply

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

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

SAIT Web Developer

Fast Track - Fall 2021

Variables - Declaration vs Assignment

Terminology, const vs let vs var.

Variables should be initially declared (a name created in memory) with a declaration keyword. This is only needed when the variable is first created. Of the three keywords available, it is recommended you try them in this order

  • const : The value of a constant can't be changed through reassignment. This is the safest way to declare a variable.
  • let : If you need to reassign a variable later (see common errors below), you should use let .
  • var : This keyword is the classic (ES5) method of declaring a variable and should be avoided.

Key Takeaways

Use strict mode whenever possible. It will make you a better (safer) coder:

At the top of your script, add:

  • Note: if you include your file with <script type="module"> , your code will run in strict mode by default.

By default, all declared variables have a value of undefined until they are assigned.

When declaring variables, start with the const keyword and use let only when you need to reassign a variable. Avoid the use of the older var keyword.

Declaration keywords ( const and let ) are only used the first time to declare the variable. After that, you can use the variable without it.

Arrays and objects defined with const are still changeable, they just can't be reassigned. In other words, the items in an array created with the const keyword can still be changed. The same is true for objects including HTML Elements.

Never explicitly assign a variable to undefined . When you need a variable to be "nothing" use null instead. The undefined data type should be reserved for use by the runtime environment.

Common assignment/declaration syntax errors

Calling a variable that hasn't been declared:

  • Probably the most common syntax error: trying to use a variable that doesn't exist. Best solution: declare the variable so it exists!
  • Note: "is not defined" does not mean undefined . This is an unfortunate choice of wording.

Missing assignment on const variable:

In Firefox:

Or, in Chrome/Node

The const keyword requires that you assign the variable with a value at the time of creation. If you need to create a variable without assigning it, use let .

Re-assigning a const variable:

You tried to reassign a constant variable. Try declaring with let if you need to reassign.

Was this page helpful?

Variable Declaration

let and const are two relatively new concepts for variable declarations in JavaScript. As we mentioned earlier , let is similar to var in some respects, but allows users to avoid some of the common “gotchas” that users run into in JavaScript.

const is an augmentation of let in that it prevents re-assignment to a variable.

With TypeScript being an extension of JavaScript, the language naturally supports let and const . Here we’ll elaborate more on these new declarations and why they’re preferable to var .

If you’ve used JavaScript offhandedly, the next section might be a good way to refresh your memory. If you’re intimately familiar with all the quirks of var declarations in JavaScript, you might find it easier to skip ahead.

var declarations

Declaring a variable in JavaScript has always traditionally been done with the var keyword.

As you might’ve figured out, we just declared a variable named a with the value 10 .

We can also declare a variable inside of a function:

and we can also access those same variables within other functions:

In this above example, g captured the variable a declared in f . At any point that g gets called, the value of a will be tied to the value of a in f . Even if g is called once f is done running, it will be able to access and modify a .

Scoping rules

var declarations have some odd scoping rules for those used to other languages. Take the following example:

Some readers might do a double-take at this example. The variable x was declared within the if block , and yet we were able to access it from outside that block. That’s because var declarations are accessible anywhere within their containing function, module, namespace, or global scope - all which we’ll go over later on - regardless of the containing block. Some people call this var -scoping or function-scoping . Parameters are also function scoped.

These scoping rules can cause several types of mistakes. One problem they exacerbate is the fact that it is not an error to declare the same variable multiple times:

Maybe it was easy to spot out for some experienced JavaScript developers, but the inner for -loop will accidentally overwrite the variable i because i refers to the same function-scoped variable. As experienced developers know by now, similar sorts of bugs slip through code reviews and can be an endless source of frustration.

Variable capturing quirks

Take a quick second to guess what the output of the following snippet is:

For those unfamiliar, setTimeout will try to execute a function after a certain number of milliseconds (though waiting for anything else to stop running).

Ready? Take a look:

Many JavaScript developers are intimately familiar with this behavior, but if you’re surprised, you’re certainly not alone. Most people expect the output to be

Remember what we mentioned earlier about variable capturing? Every function expression we pass to setTimeout actually refers to the same i from the same scope.

Let’s take a minute to consider what that means. setTimeout will run a function after some number of milliseconds, but only after the for loop has stopped executing; By the time the for loop has stopped executing, the value of i is 10 . So each time the given function gets called, it will print out 10 !

A common work around is to use an IIFE - an Immediately Invoked Function Expression - to capture i at each iteration:

This odd-looking pattern is actually pretty common. The i in the parameter list actually shadows the i declared in the for loop, but since we named them the same, we didn’t have to modify the loop body too much.

let declarations

By now you’ve figured out that var has some problems, which is precisely why let statements were introduced. Apart from the keyword used, let statements are written the same way var statements are.

The key difference is not in the syntax, but in the semantics, which we’ll now dive into.

Block-scoping

When a variable is declared using let , it uses what some call lexical-scoping or block-scoping . Unlike variables declared with var whose scopes leak out to their containing function, block-scoped variables are not visible outside of their nearest containing block or for -loop.

Here, we have two local variables a and b . a ’s scope is limited to the body of f while b ’s scope is limited to the containing if statement’s block.

Variables declared in a catch clause also have similar scoping rules.

Another property of block-scoped variables is that they can’t be read or written to before they’re actually declared. While these variables are “present” throughout their scope, all points up until their declaration are part of their temporal dead zone . This is just a sophisticated way of saying you can’t access them before the let statement, and luckily TypeScript will let you know that.

Something to note is that you can still capture a block-scoped variable before it’s declared. The only catch is that it’s illegal to call that function before the declaration. If targeting ES2015, a modern runtime will throw an error; however, right now TypeScript is permissive and won’t report this as an error.

For more information on temporal dead zones, see relevant content on the Mozilla Developer Network .

Re-declarations and Shadowing

With var declarations, we mentioned that it didn’t matter how many times you declared your variables; you just got one.

In the above example, all declarations of x actually refer to the same x , and this is perfectly valid. This often ends up being a source of bugs. Thankfully, let declarations are not as forgiving.

The variables don’t necessarily need to both be block-scoped for TypeScript to tell us that there’s a problem.

That’s not to say that a block-scoped variable can never be declared with a function-scoped variable. The block-scoped variable just needs to be declared within a distinctly different block.

The act of introducing a new name in a more nested scope is called shadowing . It is a bit of a double-edged sword in that it can introduce certain bugs on its own in the event of accidental shadowing, while also preventing certain bugs. For instance, imagine we had written our earlier sumMatrix function using let variables.

This version of the loop will actually perform the summation correctly because the inner loop’s i shadows i from the outer loop.

Shadowing should usually be avoided in the interest of writing clearer code. While there are some scenarios where it may be fitting to take advantage of it, you should use your best judgement.

Block-scoped variable capturing

When we first touched on the idea of variable capturing with var declaration, we briefly went into how variables act once captured. To give a better intuition of this, each time a scope is run, it creates an “environment” of variables. That environment and its captured variables can exist even after everything within its scope has finished executing.

Because we’ve captured city from within its environment, we’re still able to access it despite the fact that the if block finished executing.

Recall that with our earlier setTimeout example, we ended up needing to use an IIFE to capture the state of a variable for every iteration of the for loop. In effect, what we were doing was creating a new variable environment for our captured variables. That was a bit of a pain, but luckily, you’ll never have to do that again in TypeScript.

let declarations have drastically different behavior when declared as part of a loop. Rather than just introducing a new environment to the loop itself, these declarations sort of create a new scope per iteration . Since this is what we were doing anyway with our IIFE, we can change our old setTimeout example to just use a let declaration.

and as expected, this will print out

const declarations

const declarations are another way of declaring variables.

They are like let declarations but, as their name implies, their value cannot be changed once they are bound. In other words, they have the same scoping rules as let , but you can’t re-assign to them.

This should not be confused with the idea that the values they refer to are immutable .

Unless you take specific measures to avoid it, the internal state of a const variable is still modifiable. Fortunately, TypeScript allows you to specify that members of an object are readonly . The chapter on Interfaces has the details.

let vs. const

Given that we have two types of declarations with similar scoping semantics, it’s natural to find ourselves asking which one to use. Like most broad questions, the answer is: it depends.

Applying the principle of least privilege , all declarations other than those you plan to modify should use const . The rationale is that if a variable didn’t need to get written to, others working on the same codebase shouldn’t automatically be able to write to the object, and will need to consider whether they really need to reassign to the variable. Using const also makes code more predictable when reasoning about flow of data.

Use your best judgement, and if applicable, consult the matter with the rest of your team.

The majority of this handbook uses let declarations.

Destructuring

Another ECMAScript 2015 feature that TypeScript has is destructuring. For a complete reference, see the article on the Mozilla Developer Network . In this section, we’ll give a short overview.

Array destructuring

The simplest form of destructuring is array destructuring assignment:

This creates two new variables named first and second . This is equivalent to using indexing, but is much more convenient:

Destructuring works with already-declared variables as well:

And with parameters to a function:

You can create a variable for the remaining items in a list using the syntax ... :

Of course, since this is JavaScript, you can just ignore trailing elements you don’t care about:

Or other elements:

Tuple destructuring

Tuples may be destructured like arrays; the destructuring variables get the types of the corresponding tuple elements:

It’s an error to destructure a tuple beyond the range of its elements:

As with arrays, you can destructure the rest of the tuple with ... , to get a shorter tuple:

Or ignore trailing elements, or other elements:

Object destructuring

You can also destructure objects:

This creates new variables a and b from o.a and o.b . Notice that you can skip c if you don’t need it.

Like array destructuring, you can have assignment without declaration:

Notice that we had to surround this statement with parentheses. JavaScript normally parses a { as the start of block.

You can create a variable for the remaining items in an object using the syntax ... :

Property renaming

You can also give different names to properties:

Here the syntax starts to get confusing. You can read a: newName1 as ” a as newName1 ”. The direction is left-to-right, as if you had written:

Confusingly, the colon here does not indicate the type. The type, if you specify it, still needs to be written after the entire destructuring:

Default values

Default values let you specify a default value in case a property is undefined:

In this example the b? indicates that b is optional, so it may be undefined . keepWholeObject now has a variable for wholeObject as well as the properties a and b , even if b is undefined.

Function declarations

Destructuring also works in function declarations. For simple cases this is straightforward:

But specifying defaults is more common for parameters, and getting defaults right with destructuring can be tricky. First of all, you need to remember to put the pattern before the default value.

The snippet above is an example of type inference, explained earlier in the handbook.

Then, you need to remember to give a default for optional properties on the destructured property instead of the main initializer. Remember that C was defined with b optional:

Use destructuring with care. As the previous example demonstrates, anything but the simplest destructuring expression is confusing. This is especially true with deeply nested destructuring, which gets really hard to understand even without piling on renaming, default values, and type annotations. Try to keep destructuring expressions small and simple. You can always write the assignments that destructuring would generate yourself.

The spread operator is the opposite of destructuring. It allows you to spread an array into another array, or an object into another object. For example:

This gives bothPlus the value [0, 1, 2, 3, 4, 5] . Spreading creates a shallow copy of first and second . They are not changed by the spread.

You can also spread objects:

Now search is { food: "rich", price: "$$", ambiance: "noisy" } . Object spreading is more complex than array spreading. Like array spreading, it proceeds from left-to-right, but the result is still an object. This means that properties that come later in the spread object overwrite properties that come earlier. So if we modify the previous example to spread at the end:

Then the food property in defaults overwrites food: "rich" , which is not what we want in this case.

Object spread also has a couple of other surprising limits. First, it only includes an objects’ own, enumerable properties . Basically, that means you lose methods when you spread instances of an object:

Second, the TypeScript compiler doesn’t allow spreads of type parameters from generic functions. That feature is expected in future versions of the language.

using declarations

using declarations are an upcoming feature for JavaScript that are part of the Stage 3 Explicit Resource Management proposal. A using declaration is much like a const declaration, except that it couples the lifetime of the value bound to the declaration with the scope of the variable.

When control exits the block containing a using declaration, the [Symbol.dispose]() method of the declared value is executed, which allows that value to perform cleanup:

At runtime, this has an effect roughly equivalent to the following:

using declarations are extremely useful for avoiding memory leaks when working with JavaScript objects that hold on to native references like file handles

or scoped operations like tracing

Unlike var , let , and const , using declarations do not support destructuring.

null and undefined

It’s important to note that the value can be null or undefined , in which case nothing is disposed at the end of the block:

which is roughly equivalent to:

This allows you to conditionally acquire resources when declaring a using declaration without the need for complex branching or repetition.

Defining a disposable resource

You can indicate the classes or objects you produce are disposable by implementing the Disposable interface:

await using declarations

Some resources or operations may have cleanup that needs to be performed asynchronously. To accommodate this, the Explicit Resource Management proposal also introduces the await using declaration:

An await using declaration invokes, and awaits , its value’s [Symbol.asyncDispose]() method as control leaves the containing block. This allows for asynchronous cleanup, such as a database transaction performing a rollback or commit, or a file stream flushing any pending writes to storage before it is closed.

As with await , await using can only be used in an async function or method, or at the top level of a module.

Defining an asynchronously disposable resource

Just as using relies on objects that are Disposable , an await using relies on objects that are AsyncDisposable :

await using vs await

The await keyword that is part of the await using declaration only indicates that the disposal of the resource is await -ed. It does not await the value itself:

await using and return

It’s important to note that there is a small caveat with this behavior if you are using an await using declaration in an async function that returns a Promise without first await -ing it:

Because the returned promise isn’t await -ed, it’s possible that the JavaScript runtime may report an unhandled rejection since execution pauses while await -ing the asynchronous disposal of x , without having subscribed to the returned promise. This is not a problem that is unique to await using , however, as this can also occur in an async function that uses try..finally :

To avoid this situation, it is recommended that you await your return value if it may be a Promise :

using and await using in for and for..of statements

Both using and await using can be used in a for statement:

In this case, the lifetime of x is scoped to the entire for statement and is only disposed when control leaves the loop due to break , return , throw , or when the loop condition is false.

In addition to for statements, both declarations can also be used in for..of statements:

Here, x is disposed at the end of each iteration of the loop , and is then reinitialized with the next value. This is especially useful when consuming resources produced one at a time by a generator.

using and await using in older runtimes

using and await using declarations can be used when targeting older ECMAScript editions as long as you are using a compatible polyfill for Symbol.dispose / Symbol.asyncDispose , such as the one provided by default in recent editions of NodeJS.

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Daniel Rosenwasser  (58)

Last updated: Feb 08, 2024  

  • Declaration of Variables

Variables are the basic unit of storage in a programming language . These variables consist of a data type, the variable name, and the value to be assigned to the variable. Unless and until the variables are declared and initialized, they cannot be used in the program. Let us learn more about the Declaration and Initialization of Variables in this article below.

What is Declaration and Initialization?

  • Declaration of a variable in a computer programming language is a statement used to specify the variable name and its data type. Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it.
  • Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable. If the value is not assigned to the Variable, then the process is only called a Declaration.

Basic Syntax

The basic form of declaring a variable is:

            type identifier [= value] [, identifier [= value]]…];

                                                OR

            data_type variable_name = value;

type = Data type of the variable

identifier = Variable name

value = Data to be stored in the variable (Optional field)

Note 1: The Data type and the Value used to store in the Variable must match.

Note 2: All declaration statements must end with a semi-colon (;)

Browse more Topics Under Data Types, Variables and Constants

  • Concept of Data types
  • Built-in Data Types
  • Constants in Programing Language 
  • Access Modifier
  • Variables of Built-in-Datatypes
  • Assignment Statement
  • Type Modifier

Rules to Declare and Initialize Variables

There are few conventions needed to be followed while declaring and assigning values to the Variables –

  • Variable names must begin with a letter, underscore, non-number character. Each language has its own conventions.
  • Few programming languages like PHP, Python, Perl, etc. do not require to specify data type at the start.
  • Always use the ‘=’ sign to initialize a value to the Variable.
  • Do not use a comma with numbers.
  • Once a data type is defined for the variable, then only that type of data can be stored in it. For example, if a variable is declared as Int, then it can only store integer values.
  • A variable name once defined can only be used once in the program. You cannot define it again to store another type of value.
  • If another value is assigned to the variable which already has a value assigned to it before, then the previous value will be overwritten by the new value.

Types of Initialization

Static initialization –.

In this method, the variable is assigned a value in advance. Here, the values are assigned in the declaration statement. Static Initialization is also known as Explicit Initialization.

Dynamic Initialization –

In this method, the variable is assigned a value at the run-time. The value is either assigned by the function in the program or by the user at the time of running the program. The value of these variables can be altered every time the program runs. Dynamic Initialization is also known as Implicit Initialization.

In C programming language –

In Java Programming Language –

FAQs on Declaration of Variables

Q1. Is the following statement a declaration or definition?

extern int i;

  • Declaration

Answer – Option B

Q2. Which declaration is correct?

  • int length;
  • float double;
  • float long;

Answer – Option A, double, long and int are all keywords used for declaration and keywords cannot be used for declaring a variable name.

Q3. Which statement is correct for a chained assignment?

  • int x, y = 10;
  • int x = y = 10;
  • Both B and C

Answer – Option C

Customize your course in 30 seconds

Which class are you in.

tutor

Data Types, Variables and Constants

  • Variables in Programming Language
  • Concept of Data Types
  • Type Modifiers
  • Access Modifiers
  • Constants in Programming Language

Leave a Reply Cancel reply

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

Download the App

Google Play

This browser is no longer supported.

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

Declaring variables

  • 8 contributors

When declaring variables , you usually use a Dim statement. A declaration statement can be placed within a procedure to create a procedure-level variable. Or it may be placed at the top of a module , in the Declarations section, to create a module-level variable.

The following example creates the variable and specifies the String data type .

If this statement appears within a procedure, the variable strName can be used only in that procedure. If the statement appears in the Declarations section of the module, the variable strName is available to all procedures within the module, but not to procedures in other modules in the project .

To make this variable available to all procedures in the project, precede it with the Public statement, as in the following example:

For information about naming your variables, see Visual Basic naming rules .

Variables can be declared as one of the following data types : Boolean , Byte , Integer , Long , Currency , Single , Double , Date , String (for variable-length strings), String * length (for fixed-length strings), Object , or Variant . If you don't specify a data type, the Variant data type is assigned by default. You can also create a user-defined type by using the Type statement.

You can declare several variables in one statement. To specify a data type, you must include the data type for each variable.

In the following statement, the variables intX , intY , and intZ are declared as type Integer .

In the following statement, intX and intY are declared as type Variant , and only intZ is declared as type Integer .

You don't have to supply the variable's data type in the declaration statement. If you omit the data type, the variable will be of type Variant .

The shorthand to declare x and y as Integer in the statement above is:

The shorthand for the types is: % -integer; & -long; @ -currency; # -double; ! -single; $ -string

Public statement

Use the Public statement to declare public module-level variables.

Public variables can be used in any procedures in the project. If a public variable is declared in a standard module or a class module , it can also be used in any projects that reference the project where the public variable is declared.

Private statement

Use the Private statement to declare private module-level variables.

Private variables can be used only by procedures in the same module.

When used at the module level, the Dim statement is equivalent to the Private statement. You might want to use the Private statement to make your code easier to read and interpret.

Static statement

When you use the Static statement instead of a Dim statement to declare a variable in a procedure, the declared variable will retain its value between calls to that procedure.

Option Explicit statement

You can implicitly declare a variable in Visual Basic simply by using it in an assignment statement. All variables that are implicitly declared are of type Variant . Variables of type Variant require more memory resources than most other variables. Your application will be more efficient if you declare variables explicitly and with a specific data type. Explicitly declaring all variables reduces the incidence of naming-conflict errors and spelling mistakes.

If you don't want Visual Basic to make implicit declarations, you can place the Option Explicit statement in a module before any procedures. This statement requires you to explicitly declare all variables within the module. If a module includes the Option Explicit statement, a compile-time error will occur when Visual Basic encounters a variable name that has not been previously declared, or that has been spelled incorrectly.

You can set an option in your Visual Basic programming environment to automatically include the Option Explicit statement in all new modules. See your application's documentation for help on how to change Visual Basic environment options. Note that this option does not change existing code that you have written.

You must explicitly declare fixed arrays and dynamic arrays.

Declaring an object variable for automation

When you use one application to control another application's objects, you should set a reference to the other application's type library . After you set a reference, you can declare object variables according to their most specific type. For example, if you are in Microsoft Word when you set a reference to the Microsoft Excel type library, you can declare a variable of type Worksheet from within Word to represent an Excel Worksheet object.

If you are using another application to control Microsoft Access objects, in most cases, you can declare object variables according to their most specific type. You can also use the New keyword to create a new instance of an object automatically. However, you may have to indicate that it is a Microsoft Access object. For example, when you declare an object variable to represent an Access form from within Visual Basic, you must distinguish the Access Form object from a Visual Basic Form object. Include the name of the type library in the variable declaration, as in the following example:

Some applications don't recognize individual Access object types. Even if you set a reference to the Access type library from these applications, you must declare all Access object variables as type Object . Nor can you use the New keyword to create a new instance of the object.

The following example shows how to declare a variable to represent an instance of the Access Application object from an application that doesn't recognize Access object types. The application then creates an instance of the Application object.

To determine which syntax an application supports, see the application's documentation.

  • Data type summary
  • Variables and constants keyword summary
  • Visual Basic conceptual topics

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

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

IMAGES

  1. Declaration vs Assignment vs Initialization

    variable declaration vs assignment

  2. 1.7 Java

    variable declaration vs assignment

  3. 75 Declaration vs Assignment Summary

    variable declaration vs assignment

  4. Variable declaration vs assignment · Issue #712 · jashkenas

    variable declaration vs assignment

  5. JavaScript Variable Declaration VS Assignment #shorts

    variable declaration vs assignment

  6. Quick Tip: How to Declare Variables in JavaScript

    variable declaration vs assignment

VIDEO

  1. #Python Equality vs. Assignment Operator. #coding #programming #learnpython #ai #datascience

  2. C2019 11 17 BASIC variable declaration statement

  3. C++ lesson 3_Variable declaration and calculate problems

  4. Declaration & Initialisation of a variable, Define Static Variable

  5. Class02 Variables types declarations

  6. Lecture 1 of JS (Introduction of JS, variables, and datatypes)

COMMENTS

  1. Difference between declaration statement and assignment statement in C

    2 Answers Sorted by: 14 Declaration: int a; Assignment: a = 3; Declaration and assignment in one statement: int a = 3; Declaration says, "I'm going to use a variable named " a " to store an integer value." Assignment says, "Put the value 3 into the variable a ."

  2. 1.4

    One downside of assignment is that it requires at least two statements: one to define the variable, and one to assign the value. These two steps can be combined. When a variable is defined, you can also provide an initial value for the variable at the same time. This is called initialization.

  3. Explain the variable declaration, initialization and assignment in C

    A variable assignment is a process of assigning a value to a variable. For example, int height = 40; int base = 31; Rules for defining variables A variable may be alphabets, digits, and underscore. A variable name can start with an alphabet, and an underscore but, can't start with a digit. Whitespace is not allowed in the variable name.

  4. PDF Resource: Variables, Declarations & Assignment Statements

    The concept of a variable is a powerful programming idea. It's called a variable because - now pay attention - it varies. When you see it used in a program, the variable is often written like this r = 255; (r is the variable and the whole thing is the assignment statement). You get the idea from such usage that a variable is like an ...

  5. Declare vs. Assign in JavaScript

    The Difference Between Declaring and Assigning To declare a constant or a variable is to create a data object and give a name, so that you can reference it later in your code. To assign a constant or variable, on the other hand, is to give it a value. Another name for declaration, if oversimplified, could be "naming it."

  6. language design

    Variable declaration versus assignment syntax Ask Question Asked 10 years, 3 months ago Modified 2 years, 5 months ago Viewed 2k times 5 Working on a statically typed language with type inference and streamlined syntax, and need to make final decision about syntax for variable declaration versus assignment.

  7. 5.4 Variable Initialization vs. Declaration on. Assignment

    5.4.3 Explained. Declaration is to point at which you produce a variable. At the point, Java recognizes nothing about this variable, so it's necessary to specify the type. This is an only time yourself need to specify the enter since for every future time, Coffee capacity refer to all declaration to determine what the type is.

  8. Variables

    Variable Declaration Creating a variable name in memory (with or without a value). In Javascript ES6, this is accomplished with the const and let declaration keywords. Variable Assignment When we give a variable name a value using the = assignment operator. We say we've "assigned a variable". If a variable hasn't been assigned, it's value will ...

  9. Difference Between Variable Declaration vs Assignment vs ...

    Difference Between Variable Declaration vs Assignment vs Initialization? Thapa Technical 635K subscribers Join Subscribe Subscribed 6.8K views 4 years ago Welcome, what is the Variable...

  10. TypeScript: Documentation

    var a = 10; As you might've figured out, we just declared a variable named a with the value 10. We can also declare a variable inside of a function: function f() { var message = "Hello, world!"; return message; } and we can also access those same variables within other functions: function f() { var a = 10; return function g() { var b = a + 1;

  11. What exactly are C++ definitions, declarations and assignments?

    40 A definition is where a value or function is described, i.e. the compiler or programmer is told precisely what it is, e.g. int foo() { return 1; } int var; // or, e.g. int var = 5; but this is clearer. A declaration tells the compiler, or programmer that the function or variable exists. e.g. int foo(); extern int var;

  12. Declaration and Initialization of Variables: How to Declare ...

    Basic Syntax The basic form of declaring a variable is: type identifier [= value] [, identifier [= value]]…]; OR data_type variable_name = value; where, type = Data type of the variable identifier = Variable name value = Data to be stored in the variable (Optional field) Note 1: The Data type and the Value used to store in the Variable must match.

  13. 5.4 Variable Initialization vs. Declaration to. Assignment

    5.4.3 Description. Declaration are the point at which you create a variable. At this point, Jordan knowledge nothing about the variable, so it's necessary to decide the type. This is the only time you need to specify the enter since forward all future time, Native bottle refer to this declaration to determine what the type is.

  14. Differences Between Definition, Declaration, and Initialization

    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

  15. Declaration statements

    A declaration statement declares a new local variable, local constant, or local reference variable. To declare a local variable, specify its type and provide its name. You can declare multiple variables of the same type in one statement, as the following example shows: string greeting; int a, b, c; List<double> xs;

  16. Variable Declaration

    An interface type, such as IComparable or IDisposable. You can declare several variables in one statement without having to repeat the data type. In the following statements, the variables i, j, and k are declared as type Integer, l and m as Long, and x and y as Single: VB. Dim i, j, k As Integer ' All three variables in the preceding statement ...

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

    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.

  18. javascript

    21 I'm curious to know the difference between declaring a variable, and initializing a variable. e.g. var example; // this is declaring var example = "hi" // initializing? Or just "adding a value"? I don't think I'm right there, but what exactly is the definition of each? Or do they basically mean the same thing? javascript variable-declaration

  19. Declaring variables (VBA)

    01/21/2022 8 contributors Feedback In this article Public statement Private statement Static statement Option Explicit statement Show 2 more When declaring variables, you usually use a Dim statement. A declaration statement can be placed within a procedure to create a procedure-level variable.

  20. What is the difference between a definition and a declaration?

    Oct 7, 2014 at 13:52. 1. Declaration is for the compiler to accept a name (to tell the compiler that the name is legal, the name is introduced with intention not a typo). Definition is where a name and its content is associated. The definition is used by the linker to link a name reference to the content of the name.

  21. vb.net

    Variable declaration and assignment Ask Question Asked 7 years, 4 months ago Modified 7 years, 3 months ago Viewed 670 times 0 As a beginner programmer I am trying to understand the concepts of variable declaration and assigning values in Visual Basic. I am considering this code from a tutorial lesson: