7
0

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.

ArduinoでSwitch文が使えない...?

Last updated at Posted at 2018-10-17
switch(value) {
    case 1:
        while(!Serial.available());
        char temp = Serial.read();
        // 処理が続く
        break;
    case 2:
        while(!Serial.available());
        char temp = Serial.read();
        // 処理が続く
        break;
    default:
        break;

このコード、Arduinoなら問題なくコンパイルは通ります。
ですが、実際に動かすと、case 1も2もdefaultもどれにも当てはまらないということになっています。
なぜなら、switch文の中で同じ変数が複数宣言されるからです。
正直に言って、コンパイルエラー出してほしかったです。
なので、解決策としては、

switch(value) {
    case 1:
        while(!Serial.available());
        {
            char temp = Serial.read();
            // 処理が続く
        }
        break;
    case 2:
        while(!Serial.available());
        {
            char temp = Serial.read();
            // 処理が続く
        }
        // 処理が続く
        break;
    default:
        break;

となります。

意外と気づきにくいバグ(だと個人的に思っています)

7
0
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?