What this for syntex means?

Hello,

Can someone please help me understand this code? Actually, what exactly is this for doing in the setup? I don't understand this syntex. Thank you

byte Address = 0x00;
int dipSwitchPins[] = {6, 7, 8, 9, 10, 11, 12, 13};

void setup() {
  for (int Pin : dipSwitchPins) {
    pinMode(Pin, INPUT_PULLUP);
    Address = (Address << 1) | digitalRead(Pin);
  }
}

put a Serial.println(Pin) statement in the loop - it would help you understand what is going on
also print the value of Address in Hex?

I think that should read

const byte dipSwitchPins []

Hello
This sketch reads the settings of a dip switch connected to pin6 to pin13.
Have a nice day and enjoy coding in C++.

Perfect. Thank you very much. Haven't seen this kind of syntex for the for loop before. When I search, I see the result for this syntex:

for (initialization; condition; increment) {
  // statement(s);
}

Have a look here

Thank you very much. Learnt something new today :slight_smile:

Means:

  for (size_t i=0; i < sizeof dipSwitchPins / sizeof dipSwitchPins[0]; i++)
  {
    int Pin = dipSwitchPins[i];
1 Like

Besides what has been said about for syntax (thanks to all, I also learned something today!), that code snippet is computing an 8-bit address that has been configured in a dip switch connected to pins 6 thru 13. Assuming that the address will not change during the program execution, it is OK to include it in the setup

Address = (Address << 1) | digitalRead(Pin);

This shifts the value of Address one bit to the left, reads one pin and copies its value to the rightmost bit of Address. After 8 iterations this variable holds the value coming from the dip switch.

1 Like

Range based for loop C++ Range-based for loop (since C++11) - cppreference.com

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.