Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Variable initialization: Difference between revisions

From Coderwiki
Variable initialization: create page
 
m add more links
 
Line 4: Line 4:
'''Initialization''' is when we give a variable a value.
'''Initialization''' is when we give a variable a value.


In most statically-typed languages, we must first declare (create) the variable before we can give it a value. In some languages like [[Python]], however, we can initialize any variable without needing to first declare it.
In most [[Static typing|statically-typed]] languages, we must first [[Variable declaration|declare]] (create) the [[variable]] before we can give it a [[value]]. In some languages like [[Python]], however, we can initialize any variable without needing to first [[Variable declaration|declare]] it.


== How does it differ from assignment? ==
== How does it differ from assignment? ==
[[Assignment]] is also the process of giving a [[variable]] a [[value]]. So what's the difference?
[[Assignment]] is also the process of giving a [[variable]] a [[value]]. So what's the difference?


[[Assignment]] is whenever we '''change''' the [[value]] of any [[variable]], while '''initialization''' is '''only when it is first given a value'''.
[[Assignment]] is whenever we '''change''' the [[value]] of any [[variable]], while '''initialization''' is '''only when it is first given a [[value]]'''.


This means that '''initialization''' is a ''type'' of [[assignment]].
This means that '''initialization''' is a ''type'' of [[assignment]].


== Example: declaration and initialization in C ==
== Example: declaration and initialization in [[C]] ==
<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
int a;        // declaration: we create the 'a' variable
int a;        // declaration: we create the 'a' variable

Latest revision as of 17:17, 9 August 2025

Variable declaration and variable initialization are two separate terms but are often confused.

What is initialization?

edit edit source

Initialization is when we give a variable a value.

In most statically-typed languages, we must first declare (create) the variable before we can give it a value. In some languages like Python, however, we can initialize any variable without needing to first declare it.

How does it differ from assignment?

edit edit source

Assignment is also the process of giving a variable a value. So what's the difference?

Assignment is whenever we change the value of any variable, while initialization is only when it is first given a value.

This means that initialization is a type of assignment.

Example: declaration and initialization in C

edit edit source
int a;         // declaration: we create the 'a' variable
a = 72;        // initialization: we give 'a' a value
char b = 'b';  // declaration and initialization