1
1

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 5 years have passed since last update.

swich構文でローカル変数を使いたい時のメモ

Posted at

かなり初歩的なことだと思いますが、メモ。

問題

switch構文内でローカル変数を使いたい時、こんなふうに記述するとコンパイルエラーになる。

switch (cellNumber) {
    case 1:
        NSString *viewDataKey = @"Name";
        
    
}

switch構文内で変数を宣言すると、コンパイルエラーになるのは、C言語の特性(C89)を引き継いでいるから、ということなのだろうか?C++(99)であれば、これは許容されるらしい。

回避策

コンパイルエラーを回避するには2通りあって、それはこのようになる。

//switch構文のスコープが開始する前に宣言する
NSString *viewDataKey;
switch (cellNumber) {
    case 1:
        viewDataKey = @"Name";
    
}

//case内の記述を{}で囲む
switch (cellNumber) {
    case 1: {
        NSString *viewDataKey = @"Name";
        
    }
    
}

ただ、switch構文内で変数を宣言する方式(後者)は、初期化処理を飛び越えてしまう可能性がある点で、とてもこわいものなのだそうだ。

参考

1
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?