I am trying to make an Arduino Based calculator that just works with a Keypad, Arduino Uno board and a LCD screen. I found a code online and i tried to understand the code yet i diditn quite understand this part. Can anyone help?
second == 0 ? lcd.print("Invalid") : total = (float)first / (float)second;
I think that's about one of the worst examples of use/abuse of the conditional operator I could think of. Sure it's legal C, but IMHO it adds nothing to readability and only serves to obfuscate. Added to that one of the expressions has a side effect (printing to the LCD).
No wonder the OP was confused...
Normally you'd see it replacing code like this...
if (a >= b)
{
max = a;
}
else
{
max = b;
}
Which you can write more compactly as...
max = (a >= b) ? a : b;
Edit: It's A ternary operator (the only one C has) and not THE ternary operator. Ternary just means 3 arguments, as compared to the more usual binary (two arguments, +, *, > etc) and unary (!, ~, etc) that we are used to.
acanyasar:
I am trying to make an Arduino Based calculator that just works with a Keypad, Arduino Uno board and a LCD screen. I found a code online and i tried to understand the code yet i diditn quite understand this part. Can anyone help?
second == 0 ? lcd.print("Invalid") : total = (float)first / (float)second;
This is just code that produces an error when you try to divide by 0. If you do you get the reply “Invalid”.