What is the difference between variable declaration and variable definition in programming?

Solar: "The terms "variable declaration" and "variable definition" are often used, but what's the difference between them?


Are variable declaration and variable definition completely the same thing? Don't they both create variables?


Or is there some difference between them?


Why do we have the words "variable declaration" and "variable definition"?


Variable declaration seems somewhat understandable, but "variable definition" sounds like a difficult term.


If we look it up in a dictionary, will we understand the meaning of "variable definition"?





Aletha: "Are you talking about the difference between variable declaration and variable definition? When people say variable definition, it may sound complicated, but it's not really. However, even if you look it up in a Japanese dictionary, you probably won't find an explanation of variable definition. That's because it's a term that has been given a specific meaning in the world of programming.


So, Solar, you're right that int x; is declaring an int variable x.


Once you declare a variable, you can use it as an int variable in subsequent lines. The purpose of defining a variable is to allocate memory for it, and in this case, int x; allocates a 4-byte memory space for variable x, which can then be used to store integer data."


Here is the code:


#include <stdio.h>


int main(void) {



int x;


x=5;


printf("%d\n", x);


return 0;

}


Program Output:


5


Solar: "we executed the int declaration 'int x;


So, we can use 'x' as a variable in the following lines like 'x=5;' or 'printf("%d\n", x);"


Aletha: "Yes, that's right. 'x' is an int variable, and in this program, it will be allocated 4 bytes of memory space.


When the line


int x;


x=5;


is executed,


he data '00000000 00000000 00000000 000000101' will be stored in the 4 bytes of memory allocated for 'x'."


Solar: "I see."


Aletha: "When 'int x;' is executed, 'x' is assigned to manage a certain 4-byte memory space, and its role as a variable is determined."


"As you can see, declaring a variable named x involves allocating memory to it and defining what role it plays is known as the definition of the variable x. To put it simply, variable declaration is about naming the variables used in the program, while variable definition is about allocating memory to the variables. That's right, Solar."


"I see. So, deciding on the name of variable x and defining what role it plays are two different things. I understand now," replied Solar.


  • Xで共有
  • Facebookで共有
  • はてなブックマークでブックマーク

作者を応援しよう!

ハートをクリックで、簡単に応援の気持ちを伝えられます。(ログインが必要です)

応援したユーザー

応援すると応援コメントも書けます

新規登録で充実の読書を

マイページ
読書の状況から作品を自動で分類して簡単に管理できる
小説の未読話数がひと目でわかり前回の続きから読める
フォローしたユーザーの活動を追える
通知
小説の更新や作者の新作の情報を受け取れる
閲覧履歴
以前読んだ小説が一覧で見つけやすい
新規ユーザー登録無料

アカウントをお持ちの方はログイン

カクヨムで可能な読書体験をくわしく知る