-2

In the video [“Hello, world” from scratch on a 6502 — Part 1] by youtuber Ben Eater he shows a line of code 10 minutes 30 seconds into the video that uses an expressioin I simply can't find.

I've tried finding it in the arduino documentation website, tried searching it directly and I haven't found it on stackoverflow either... here is the code:

const char ADDR[]={22, 24, 26...} // these are pins in the Arduino Mega

void setup() {
    for (int n = 0; n < 16; n += 1) {
        pinMode(ADDR[n], INPUT);
    }
    Serial.begin(57600);
}

void loop() {
    for (int n = 0; n < 16; n +=1) {
        int bit = digitalRead(ADDR[n]) ? 1 : 0;
        Serial.print(bit);
    }
    Serial.println();
}

In the line of code int bit = digitalRead(ADDR[n]) ? 1 : 0; is the expression I haven't seen anywhere else. It's supposed to mean if digitalRead(ADDR[n]) is true then add a 1 if not add a 0 then asign it to the integer variable bit. I haven't seen the ? True : False expression anywhere else and I want to know where its reference is and where to use it and stuff like that. I don't even know what it's called!

Thank you if you answered! I'm still learning and I think tricks like these will help me immensely.

Ele1729
  • 1
  • 1

1 Answers1

1

Expressions in C++ are formed by combining operands and operators.

What the operators do can be found in the C++ reference.

This is the conditional or ternary operator. It is basically a short if else.

(expression 1) ? expression 2 : expression 3

If expression 1 is true, expression 2 is evaluated. If expression 1 is false, expression 3 is evaluated.

int bit = digitalRead(ADDR[n]) ? 1 : 0;

will assign 1 to bit if digitalRead(ADDR[n]) returns HIGH and 0 else.

This expression doesn't make any sense though as digitalRead will return 1 or 0 anyway.

int bit = digitalRead(ADDR[n]); does the same

He is mistaken about digitalRead returning a boolean. It returns an integer.

https://github.com/arduino/ArduinoCore-avr/blob/60f0d0b125e06dbf57b800192c80e5f60d681438/cores/arduino/wiring_digital.c#L165

Even if digitalRead would return a boolean, false evaluates to 0 and true to 1 so storing that into an integer is absolutely no problem. It would implicitly be casted to integer and the value wouldn't change.

Piglet
  • 27,501
  • 3
  • 20
  • 43