2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C言語】初期化と代入の違いについて

Last updated at Posted at 2023-09-02

【C言語】初期化と代入について

何が違うのか分からなかったので、忘れないようアウトプット。

変数は、作られたときに不定値(ゴミ値)が入ります。

不定値(ゴミ値)
#include <stdio.h>

int main(void){

/* xに何も値を入れない */
 int x;

 printf("%d", x);
 return 0;
}

実行結果
/* 不定値(ゴミ値)が出てくる */
0

int x;で生成したときに入っている不定値(ゴミ値)が出力される。
実行時にエラーが発生したりする原因になるみたいなので、気を付けたいです。

初期化子を使った初期化

データ型 変数;生成と共に入れるのことを初期化子と呼びます。
データ型 変数 = 値(初期化子)
データ型 変数 = 値(初期化子), 変数 = 値(初期化子)....なども可能。

初期化
#include <stdio.h>

int main(void){

/* 変数を作り、値も同時に入れる */
/*   20 と x-12は初期化子(値)   */
 int x = 20, y = x-12;    

 printf("xの整数は:%d\n",x);
 printf("yの整数は:%d\n",y);
 return 0;
}
xの整数は:20
yの整数は:8

データ型と変数を宣言後、値を初期化(代入)

#include <stdio.h>

int main(void){

/* データ型と変数宣言 */
 int x,y;

/* 値を代入して、初期化する */
 x = 20;
 y = x - 12;

 printf("xの整数は:%d\n",x);
 printf("yの整数は:%d\n",y);
 return 0;
}
xの整数は:20
yの整数は:8

値を代入するタイミングが違う!

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?