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 an object is defined, you can optionally give it an initial value. The process of specifying an initial value for an object is called initialization , and the syntax used to initialize an object is called an initializer .

In the above initialization of variable width , { 5 } is the initializer, and 5 is the initial value.

Different forms of initialization

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 (and is therefore most consistent), 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

Julian Kühnel

Quick Tip: How to Declare Variables in JavaScript

Share this article

code on a screen

Difference between Declaration, Initialization and Assignment

Declaration types, accidental global creation, hoisting and the temporal dead zone, frequently asked questions (faqs) about javascript variable declaration.

When learning JavaScript one of the basics is to understand how to use variables. Variables are containers for values of all possible types, e.g. number, string or array (see data types ). Every variable gets a name that can later be used inside your application (e.g. to read its value).

In this quick tip you’ll learn how to use variables and the differences between the various declarations.

Before we start learning the various declarations, lets look at the lifecycle of a variable.

Variable lifecycle flowchart

  • Declaration : The variable is registered using a given name within the corresponding scope (explained below – e.g. inside a function).
  • Initialization : When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.
  • Assignment : This is when a specific value is assigned to the variable.
Note : while var has been available in JavaScript since its initial releast, let and const are only available in ES6 (ES2015) and up. See this page for browser compatibility.

This declaration is probably the most popular, as there was no alternative until ECMAScript 6 . Variables declared with var are available in the scope of the enclosing function. If there is no enclosing function, they are available globally.

This will cause an error ReferenceError: hello is not defined , as the variable hello is only available within the function sayHello . But the following will work, as the variable will be declared globally – in the same scope console.log(hello) is located:

let is the descendant of var in modern JavaScript. Its scope is not only limited to the enclosing function, but also to its enclosing block statement. A block statement is everything inside { and } , (e.g. an if condition or loop). The benefit of let is it reduces the possibility of errors, as variables are only available within a smaller scope.

This will cause an error ReferenceError: hello is not defined as hello is only available inside the enclosing block – in this case the if condition. But the following will work:

Technically a constant isn’t a variable. The particularity of a constant is that you need to assign a value when declaring it and there is no way to reassign it. A const is limited to the scope of the enclosing block, like let .

Constants should be used whenever a value must not change during the applications running time, as you’ll be notified by an error when trying to overwrite them.

You can write all of above named declarations in the global context (i.e. outside of any function), but even within a function, if you forget to write var , let or const before an assignment, the variable will automatically be global.

The above will output Hello World to the console, as there is no declaration before the assignment hello = and therefore the variable is globally available.

Note: To avoid accidentally declaring global variables you can use strict mode .

Another difference between var and let / const relates to variable hoisting . A variable declaration will always internally be hoisted (moved) to the top of the current scope. This means the following:

is equivalent to:

An indication of this behavior is that both examples will log undefined to the console. If var hello; wouldn’t always be on the top it would throw a ReferenceError .

This behavior called hoisting applies to var and also to let / const . As mentioned above, accessing a var variable before its declaration will return undefined as this is the value JavaScript assigns when initializing it.

But accessing a let / const variable before its declaration will throw an error. This is due to the fact that they aren’t accessible before their declaration in the code. The period between entering the variable’s scope and reaching their declaration is called the Temporal Dead Zone – i.e. the period in which the variable isn’t accessible.

You can read more about hoisting in the article Demystifying JavaScript Variable Scope and Hoisting .

To reduce susceptibility to errors you should use const and let whenever possible. If you really need to use var then be sure to move declarations to the top of the scope, as this avoids unwanted behavior related to hoisting.

What is the difference between variable declaration and initialization in JavaScript?

In JavaScript, variable declaration and initialization are two distinct steps in the process of using variables. Declaration is the process of introducing a new variable to the program. It’s done using the var, let, or const keywords. For example, let x; Here, x is declared but not defined. It’s like telling the program, “Hey, I’m going to use a variable named x.” Initialization, on the other hand, is the process of assigning a value to the declared variable for the first time. For example, x = 5; Here, x is initialized with the value 5. It’s like telling the program, “The variable x I told you about earlier? It’s value is 5.”

Can I declare a variable without initializing it in JavaScript?

Yes, in JavaScript, you can declare a variable without initializing it. When you declare a variable without assigning a value to it, JavaScript automatically assigns it the value of undefined. For example, if you declare a variable like this: let x; and then try to log x to the console, you’ll get undefined because x has been declared but not initialized.

What happens if I use a variable without declaring it in JavaScript?

In JavaScript, if you use a variable without declaring it first, you’ll get a ReferenceError. This is because JavaScript needs to know about a variable before it can be used. If you try to use a variable that hasn’t been declared, JavaScript doesn’t know what you’re referring to and throws an error. For example, if you try to log x to the console without declaring x first, you’ll get a ReferenceError: x is not defined.

What is the difference between var, let, and const in JavaScript variable declaration?

In JavaScript, var, let, and const are all used to declare variables, but they have different behaviors. var is function-scoped, meaning a variable declared with var is available within the function it’s declared in. let and const are block-scoped, meaning they’re only available within the block they’re declared in. Additionally, const is used to declare constants, or variables that can’t be reassigned after they’re initialized.

Can I redeclare a variable in JavaScript?

In JavaScript, whether you can redeclare a variable depends on how you initially declared it. If you declared a variable with var, you can redeclare it. However, if you declared a variable with let or const, you can’t redeclare it within the same scope. Attempting to do so will result in a SyntaxError.

What is hoisting in JavaScript?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. This means that you can use variables and functions before they’re declared. However, only the declarations are hoisted, not initializations. If a variable is declared and initialized after using it, the variable will be undefined.

What is the scope of a variable in JavaScript?

The scope of a variable in JavaScript determines where that variable can be accessed from within your code. Variables declared with var have function scope, meaning they can be accessed anywhere within the function they’re declared in. Variables declared with let and const have block scope, meaning they can only be accessed within the block they’re declared in.

What is the difference between null and undefined in JavaScript?

In JavaScript, null and undefined are both special values that represent the absence of a value. However, they’re used in slightly different ways. undefined is the value assigned to a variable that has been declared but not initialized. null, on the other hand, is a value that represents no value or no object. It needs to be assigned to a variable explicitly.

Can I use special characters in variable names in JavaScript?

In JavaScript, variable names can include letters, digits, underscores, and dollar signs. They must begin with a letter, underscore, or dollar sign. Special characters like !, @, #, %, etc., are not allowed in variable names.

What is a global variable in JavaScript?

A global variable in JavaScript is a variable that’s declared outside of any function or block. Because it’s not tied to a function or block, a global variable can be accessed from anywhere in your code. However, global variables can lead to issues with naming conflicts and are generally best avoided when possible.

Julian is a passionate software developer currently focusing on frontend technologies and loves open source.

SitePoint Premium

Understanding Variables in C++: From Declaration to Initialization

Understanding Variables in C++: From Declaration to Initialization

In C++, a variable is essentially a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. All operations performed on a variable affect the memory location it refers to

Continue to delete post?

Algogenz logo

3m · 6 min read

In C++, variables are fundamental building blocks that allow us to store and manipulate data. This article will take you through the basics of declaring and initializing variables, providing you with a solid foundation in C++ programming.

What Are Variables?

Before we delve into the specifics of variables, let's understand what they are. In C++, a variable is essentially a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. All operations performed on a variable affect the memory location it refers to.

Declaring Variables

The first step in working with variables is to declare them. Declaration simply tells the compiler that we intend to use a particular identifier as a variable name, and informs it about the type of data that the variable will hold. Here's an example of declaring three integer variables: a, b, and c:

We can also declare multiple variables at once:

A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore _ character. However, the name must not start with a number.

Initializing Variables

Once a variable has been declared, we can assign it a value, a process known as initialization. There are several ways to initialize variables in C++:

Assignment Initialization: After declaring a variable, we can assign a value to it using the = operator. This is known as assignment initialization.

Copy Initialization: We can combine the declaration and initialization into a single statement using the = operator.

Direct Initialization: We can use parentheses () to initialize a variable during its declaration.

Uniform Initialization (List Initialization): Introduced in C++11, this method uses curly braces {} for initialization. It is considered safer and more consistent compared to the other methods.

Value Initialization: If we use empty braces {} during initialization, the variable is value-initialized. This means that the variable is initialized to zero (or to false for booleans).

Dynamic Initialization: This is where the variable is assigned a value at runtime. The value of this variable can be altered every time the program is run.

Types of Variables

In C++, there are three types of variables based on the scope of variables:

1. Local Variables: A variable defined within a block or method or constructor is called a local variable. These variables are created when entered into the block or the function is called and destroyed after exiting from the block or when the call returns from the function. The scope of these variables exists only within the block in which the variable is declared.

2. Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor, or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables.

3. Global Variables: Global variables are those which are declared outside all functions. They are accessible throughout the entire program. They are initialized only once and retain their values until the program ends. However, a program can have the same name for local and global variables but the value of the local variable inside a function will take precedence.

4. Static Variables: Static variables are local variables that retain their values between function calls. They are initialized only once, and their values are set to zero if not explicitly initialized. Static variables are created only once, and they are not destroyed until the end of the program. They are used when you want to retain the value of a variable between multiple function calls.

Using Variables

Once a variable has been declared and initialized, we can use it in our code. We can perform arithmetic operations, compare it with other variables, or even pass it to functions. Here's an example:

In this example, we declare and initialize two integer variables  a  and  b . We then increment  a  by 1 and subtract  b  from  a , storing the result in another variable  result . Finally, we print out the value of  result .

Understanding Variable Scope

The scope of a variable is the part of the program where the variable can be accessed. It defines the visibility and lifetime of a variable. There are three types of scopes:

1. Global Scope: A global variable is one that is declared outside of any class, function, or namespace. Its scope extends from the point of declaration to the end of the file in which they are declared. Global variables are accessible throughout the entire program.

2. Local Scope: A local variable is one that is declared within a function or a block. Its scope is limited to the block, statement, or expression in which it is declared. Once the control goes out of the block, the local variable is destroyed.

3. Namespace Scope: A variable that is declared within a namespace, outside of any class or function definition, is visible from its point of declaration to the end of the namespace.

It's worth noting that a variable declared in a function with the same name as a global variable will take precedence over the global variable within that function. This is known as shadowing. To access the global variable within the function, you would use the scope resolution operator.

Lifetime of Variables

The lifetime of a variable is the period during which the variable is in a valid state. For local non-static variables, the lifetime is limited to their scope. When the scope ends, the variable is destroyed. For global variables, the lifetime is the entire program.

For static local variables, the lifetime is the entire program, similar to global variables. However, unlike global variables, static local variables are only initialized once, and their values persist between function calls.

Understanding variables, their declaration, initialization, and usage is crucial in C++ programming. As you continue to learn C++, you'll encounter more complex uses of variables, but the basic principles remain the same. Remember, a well-understood variable can make your code cleaner, easier to read, and less prone to errors.

  • Programming Languages
  • Web Development
  • Data Structures

Get the best experience on this app by signing in.

Continue with Google

404 Not found

DEV Community

DEV Community

Shameel Uddin

Posted on Nov 6, 2023

JavaScript Variable: Declaration vs. Initialization

In programming, variable declaration and initialization are two fundamental concepts that involve creating and assigning values to variables. Here's what each term means:

Variable Declaration:

  • Declaring a variable means, that we are just creating the container at the moment.
  • var is the keyword that is used to declare the variable.
  • Name of the variable is shameel . You can give any name here considering it is not against the rules of variable in JavaScript.

Image description

Variable Initialization:

  • Initializing a variable means, we assign a value to it right after its creation in one command/line

You can combine variable declaration and initialization in a single step as well:

Image description

Declaration and Initialization for var, let and const

  • You can declare a variable with let .
  • You can initialize a variable with let .
  • You can both declare and initialize a variable with let in a single step.

var (not recommended in modern JavaScript):

  • You can declare a variable with var .
  • You can initialize a variable with var .
  • You can both declare and initialize a variable with var in a single step.
  • You can declare a variable with const , but you must initialize it at the same time. You cannot declare a const variable without an initial value.
  • You cannot reassign a new value to a const variable after it's been initialized. It remains constant.

In summary, you can both declare and initialize variables using let and var . With const , you must declare and initialize the variable in a single step, and it cannot be reassigned after initialization.

It's important to note that not all programming languages handle variable declaration and initialization in the same way, and the rules can vary. Some languages require variables to be explicitly declared before use, while others may allow variables to be implicitly declared upon initialization. Understanding these concepts is essential for writing correct and efficient code in any programming language.

Happy coding! 🚀👨‍💻🌐

Follow me for more such content: LinkedIn: https://www.linkedin.com/in/shameeluddin/ Github: https://github.com/Shameel123

Top comments (2)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

voko profile image

  • Joined Oct 12, 2023

Why did you decide that "var" is obsolete? With "var" you can write code like a human and not like a machine.

shameel profile image

  • Education Masters in Computer and Information Engineering
  • Work Software Engineer
  • Joined May 7, 2022

For starters, I did not "decide".

I presented my PoV just like you did. :)

Stay humble.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

anmolbaranwal profile image

30+ app ideas with complete source code

Anmol Baranwal - Apr 17

mikeyoung44 profile image

DreamGaussian: Generative Gaussian Splatting for Efficient 3D Content Creation

Mike Young - Apr 11

On the Efficiency of Convolutional Neural Networks

kutt27 profile image

Difference between var and let in Javascript

Amal Satheesan - Apr 10

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Search anything:

Definition vs Declaration vs Initialization in C/ C++

C++ c programming software engineering.

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

In this article, we have covered the differences between 3 core terms Definition, Declaration and Initialization in C and C++ along with code snippets.

Table of contents:

  • Declaration
  • Initialization

Conclusion / Table of Differences

To understand the difference between the two we should first understand each term independently.So,here we go.

1. Declaration

Declaration of a variable is generally a introduction to a new memory allocated to something that we may call with some name.

Properties of declaration - 1.Memory creation occurs at the time of declaration itself. 2.Variables may have garbage values. 3.Variables cannot be used before declaration.

2. Definition

In declaration, user defines the previously declared variable.

3. Initialisation

Initialisation is nothing but assigning the value at the time of declaration.

From the above explanation we can conclude the following-

  • Declaration is just naming the variable.
  • Definition does not means declaration '+' Initialisation as definition might be without initialisation.
  • Initialisation is assigning valueto the declared variable. (At the time of declaration)

With this article at OpenGenus, you must have the complete idea of Definition vs Declaration vs Initialization in C/ C++.

OpenGenus IQ: Computing Expertise & Legacy icon

  • 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

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.

difference between declaration assignment and initialization

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.

404 Not found

BenchResources.Net

Java tutorial for beginners, java – declaration, definition, initialization and instantiation, instance of class.

December 19, 2016 SJ Interview Questions , Java Basics 0

In this article, we will discuss some of the key terms used in programming languages.

Often, we get confused with few terms in the programming world;

  • Declaration
  • Defining or definition
  • Initialization
  • Instantiation
  • Instance of a class
  • First, let us try to understand what all a class contains in OOPS or in specific Java;
  • member variables (fields)
  • behavior (methods or functions)

Student.java

Let us go through each terms in details with example & explanation;

1. Declaration:

  • So when a member variables is declared without any value associated with it OR
  • When method is just declared (method prototype with no body & ending with semi-colon(;))
  • Then, it is simply referred as declaration
  • Example: interface and abstract methods inside abstract class
  • Note: all methods inside interface are abstract till Java 7 version

Example 1: with interface

Student1.java

Example 2: with abstract class

Student2.java

2. Definition or Initialization:

  • Now, when we declare any member variable & assign some values to variables, then member variable is said to defined or initialized
  • Also, if a method is defined with body (with logic inside opening-closing curly braces), then it is said to be method definition (as against abstract method when we said just declaration)
  • Examples:  concrete classes

3. Instantiation:

  • When a blue-print or full-fledged class is defined with its member variables and method definition, then we need to create or instantiate an object; so as to access all possible variables and methods
  • Instantiate is the very correct word used (instead of create, which is used to understand in laymen terms)

4. Instance of a class:

  • Whenever we instantiate or create an object of a class, then that particular reference variable is referred as instance of that class
  • Generally, when we instantiate an object, there is always new operator associted with it for the creation of new object
  • Using instanceOf operator , we can always check or verify whether particular reference variable is an instance of a class or NOT

Its time for you folks to reply back with your comments and sugestion

Happy Coding !! Happy Learning !!

Related posts:

  • Java – How to construct an immutable class ?
  • Java – Interview Question and Answers on Constructor
  • Java – Switch Case statements with String
  • Java features version-wise

Trending Articles on Technical and Non Technical topics

  • 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

IMAGES

  1. Difference between Declaration and Definition and Initialization in C++

    difference between declaration assignment and initialization

  2. Difference Between Variable Declaration vs Assignment vs Initialization?

    difference between declaration assignment and initialization

  3. Javascript variable declaration in function

    difference between declaration assignment and initialization

  4. What are JavaScript Variables and How to define, declare and

    difference between declaration assignment and initialization

  5. Declaration vs Assignment vs Initialization

    difference between declaration assignment and initialization

  6. Variable Declaration and Initialization in C Language| Declaration vs Definition vs Initialization

    difference between declaration assignment and initialization

VIDEO

  1. DIFFERENCE BETWEEN DECLARATION & SUCCESSION WITH PROCEDURE

  2. Declaration Vs Initialization in any Programming Language #rprogramming #code #cprogramming

  3. Variable Declaration, Initialization, Assignment Lecture

  4. Variable declaration, Assignment statement and user-defined data type

  5. #C Difference between Variable Declaration and Initialization

  6. Declaration vs initialization #javascript #javascript_tutorial #javascriptinterview #coding

COMMENTS

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

  2. Differences Between Definition, Declaration, and Initialization

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

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

  4. 1.4

    1.4 — Variable assignment and initialization. Alex March 22, 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 ...

  5. Initialization, declaration and assignment terms in Java

    Initialization, declaration and assignment terms in Java. A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied ...

  6. Quick Tip: How to Declare Variables in JavaScript

    Difference between Declaration, Initialization and Assignment. Before we start learning the various declarations, lets look at the lifecycle of a variable. Declaration: The variable is registered ...

  7. Understanding Variables in C++: From Declaration to Initialization

    This is known as assignment initialization. int a; a = 5; // assignment initialization 5. Copy Initialization: We can combine the declaration and initialization into a single statement using the = operator. int b = 5; // copy initialization. Direct Initialization: We can use parentheses to initialize a variable during its declaration.

  8. A Guide to Java Initialization

    In Java, an initializer is a block of code that has no associated name or data type and is placed outside of any method, constructor, or another block of code. Java offers two types of initializers, static and instance initializers. Let's see how we can use each of them. 7.1. Instance Initializers.

  9. 5.4 Variable Initialization vs. Declaration vs. Assignment

    5.4.3 Declaration. Declaration is this point at who to create a variable. At this point, Java knows nothing about the variable, so it's necessary to please the type. This is this alone time you need to specify the type since for all future time, Java can refer to this declaration to determine what of type is.

  10. JavaScript Variable: Declaration vs. Initialization

    var (not recommended in modern JavaScript): You can declare a variable with var. You can initialize a variable with var. You can both declare and initialize a variable with var in a single step. Example: var x; // Declaration x = 10; // Initialization var y = 20; // Declaration and initialization in one step.

  11. Definition vs Declaration vs Initialization in C/ C++

    In this article, we have covered the differences between 3 core terms Definition, Declaration and Initialization in C and C++ along with code snippets. Table of contents: Declaration; Definition; Initialization; Conclusion / Table of Differences; To understand the difference between the two we should first understand each term independently.So ...

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

    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. Why declare a variable in one line, and assign to it in the next?

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

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

  15. Difference between declaration statement and assignment statement in C

    Declaration: int a; Assignment: a = 3; Declaration and assignment stylish one declaration: int a = 3; Declaration declares, "I'm going at getting a variable named "a" to store an integer value."Assignment declares, "Put the value 3 into the variably a." (As @delnan points out, my last example is technically initialization, since you're mentioning what value the variable starts equipped, rather ...

  16. Java

    2. Definition or Initialization: Now, when we declare any member variable & assign some values to variables, then member variable is said to defined or initialized; Also, if a method is defined with body (with logic inside opening-closing curly braces), then it is said to be method definition (as against abstract method when we said just ...

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

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

  18. c#

    Declaring - Declaring a variable means to introduce a new variable to the program. You define its type and its name. int a; //a is declared. Instantiate - Instantiating a class means to create a new instance of the class. Source. MyObject x = new MyObject(); //we are making a new instance of the class MyObject.

  19. Variable Instantiation on Declaration vs. on Constructor in Java

    1. Introduction. There is uncertainty among Java developers on whether to initialize variables when they are declared or in a constructor. In this tutorial, we'll take a look at what happens when we initialize variables at their declaration or in a constructor. We'll try to point out some differences and similarities between them if they ...

  20. Difference between declaration statement and assignment statement in C

    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." (As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts with, rather than changing the value.

  21. Is there a difference between initializing a variable and assigning it

    Assuming a purely non-optimizing compiler, is there any difference in machine code between initializing a variable and assigning it a value after declaration? Initialization method: int x = 2; Assignment method: int x; x = 2; I used GCC to output the assembly generated for these two different methods and both resulted in a single machine ...