我的朋友给了我这个Arduino代码:
int button;
void setup(){
pinMode(12, INPUT);
}
void loop(){
for(button; button == HIGH; button == digitalRead(12)) { //This line
//Do something here
}
}
用"this line"注释的行我看不清楚。
我经常看到这样的for
循环:
for (init; condition; increment)
也有不同的用法,如:
for(int i=0; i<n; i++){}
for(;;){}
等等,但是我从来没有见过像我从朋友那里得到的代码。
它确实在Arduino IDE上编译,那么这个特定的for
循环的含义是什么?
换句话说,它是什么样的循环,它是如何工作的?
这个循环:
for(button; button == HIGH; button == digitalRead(12))
等价于:
button; // does nothing - should probably be `button = HIGH;` ?
while (button == HIGH) // break out of loop when button != HIGH
{
//do something here
button == digitalRead(12); // comparison - should probably be assignment ?
}
注意:我怀疑整个循环是有bug的,应该是:
for (button = HIGH; button == HIGH; button = digitalRead(12))
// do something here
首先,让我们从字面上解释一下。转换为while循环:
button; // does nothing
while(button == HIGH) { // clear
// do stuff
button == digitalRead(12); // same as digitalRead(12);
}
这段代码真的应该会引发很多IDE或编译器警告。不管怎样,我的答案是正确的,这就是它的字面意思。注意,button == digitalRead(12)
是有效的,但对比较结果没有任何影响。
很可能代码有bug。一个假设是==
应该是=
。