Syntax question, "?"

in the last line of this sketch, what is going on with the question mark ? (return digit == 10 **?** 0 : digit;) . The function has counted the number of "clicks" of a rotary phone dial switch, but I'm not clear what the added code after the equals operator does.

#include <Arduino.h>
#include "RotaryPhoneDialDecoder.h"

RotaryPhoneDialDecoder::RotaryPhoneDialDecoder(uint8_t _diallingSignalPin, uint8_t _digitSignalPin) {
  diallingSignalPin = _diallingSignalPin;
  digitSignalPin = _digitSignalPin;
}

void RotaryPhoneDialDecoder::setup() {
  pinMode(diallingSignalPin, INPUT_PULLUP);
  pinMode(digitSignalPin, INPUT_PULLUP);
}

bool RotaryPhoneDialDecoder::isDialling() {
  return digitalRead(diallingSignalPin) == LOW; // diallingSignalPin is low as soon as dialling has started (and during the complete dial process)
}

// Return currently dialled digit (0-9), or -1 if the digit was not recognized
// correctly (0 or more than 10 pulses detected). Dialling must already have
// started (`diallingSignalPin` active).
//
// `diallingSignalPin` is assumed to be active-low; for `digitSignalPin` it
// doesn’t matter (edge detection works with both active-low and active-high).
int8_t RotaryPhoneDialDecoder::readDigit() {
  uint8_t digit = 0, last = LOW, current = LOW;
  while (digitalRead(diallingSignalPin) == LOW) {
    current = digitalRead(digitSignalPin);

    // Count how often digitSignalPin toggles its state (edge detection).
    if (last == LOW && current == HIGH) digit++;

    last = current;
    delay(10);
  }
  if (digit < 1 || digit > 10) return -1;
  return digit == 10 ? 0 : digit;
}

Google "C ternery operator"

return digit == 10 ? 0 : digit;
is quivalent to

if (digit == 10)
{
  return 0;
}
else
{
  return digit;
}
1 Like

Thank you!

? : is a ternary operator, probably the only one in C/C++ . Although it is not the only ternary operator, it often gets called THE ternary operator. It is sometimes called the Elvis operator (turn the page sideways and squint a lot).

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