Would someone please help me understand this line of code?  command = switchingChannel ?

Would someone please help me understand this line of code?

command = switchingChannel ? 110 : 0;

Specifically, the ? and : are what I am not understanding. Thanks.

It’s a special syntax “if else” statement

The ? and : are called the ternary operator. It’s in the form of: ? : . If the expression part evaluates to true (i.e. any non-zero value), the value after the ‘?’ is used, otherwise the value after the ‘:’ is used. So - in this specific example, if switchingChannel is anything but zero, command would be set to 110 - otherwise it would be set to 0.
Hope this makes sense! :slight_smile:

@Eran_Rundstein @Christopher_Smolinsk Thank you for the quick response. Are there performance advantages to coding like this in Arduino, rather than using the if() like I’m used to?

Happy to help. No performance advantages - its just syntactic sugar.

It’s called the ternary operator, because it has three clauses: the Test value, the True value, and the False value.

It’s the same size and speed as an “if” statement.

The only thing you can do with it that you can’t do with if-then-else is initialize the value of a constant to different values:

const float weightFactor = isMetric? 2.2 : 1.0;

I have another area in need of clarity, and it’s in regards to typedefs/enums. The code below is for sending a packet using a cheap radio module. However it doesn’t allow me to pass info to it, such as another address. In this case the address it is sending to is “bd001”.

void send_packet() {
Mirf.setTADDR((byte *)“bd001”);
Mirf.send((byte *)&packet);
}

I would like to create a list of possible address to send data to like this:

 address[] = { "bd002", "bd003", "bd004" };

And call it like this in my loop:

 send_packet(address[x]);

How can I code this correctly? The MiRF library method of setting the TX address reads a byte at a time. Are the " " important to making this operate properly?

After a bit more research, I know that * & are pointers, yet I don’t understand their true function. In this case, I realize that the Mirf.setTADDR((byte *)“bd001”); is reading a string one byte at a time.

So if I’m thinking this through correctly, then my code above needs to be this in order to have a list of addresses to transmit to:

char* address[] = { “bd002”, “bd003”, “bd004” };
Mirf.setTADDR((byte *)address[x]);