Variable declaration: Difference between revisions
From Coderwiki
More actions
create Variable declaration |
m Variable declaration: rename example section to 'Example: declaration and initialization in C' |
||
| Line 8: | Line 8: | ||
Of course, it will be given some sort of [[initial value]], as it [[Memory allocation|allocates the memory]] and there must be something at that [[memory location]]. It's just that most [[Programming language|programming languages]] will give the [[variable]] a value such as [[undefined]], [[null]] or possibly through a 'variable not defined' [[error]] or [[exception]] if you try to access the data. Other languages like [[C]] may just return [[garbage data]] if you try to access its [[value]]. | Of course, it will be given some sort of [[initial value]], as it [[Memory allocation|allocates the memory]] and there must be something at that [[memory location]]. It's just that most [[Programming language|programming languages]] will give the [[variable]] a value such as [[undefined]], [[null]] or possibly through a 'variable not defined' [[error]] or [[exception]] if you try to access the data. Other languages like [[C]] may just return [[garbage data]] if you try to access its [[value]]. | ||
== Example: declaration 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 21:27, 8 August 2025
While the two terms are often used synonymously, there is a difference between variable declaration and variable initialization.
What is declaration?
edit edit sourceDeclaration is the process of creating a variable.
When we declare a variable, we essentially create it. We don't give it a value, only say that it exists.
Of course, it will be given some sort of initial value, as it allocates the memory and there must be something at that memory location. It's just that most programming languages will give the variable a value such as undefined, null or possibly through a 'variable not defined' error or exception if you try to access the data. Other languages like C may just return garbage data if you try to access its value.
Example: declaration and initialization in C
edit edit sourceint a; // declaration: we create the 'a' variable
a = 72; // initialization: we give 'a' a value
char b = 'b'; // declaration and initialization