what is this command "a ? x : y"

Hi,

I'm trying to understand some source code and i came across this:

pn532_packetbuffer[2] = (keyNumber) ? MIFARE_CMD_AUTH_A : MIFARE_CMD_AUTH_B;


I have never seen this command before. Can somebody please explain it to me?

What i already know is:
packetbuffer is just an integer array
keynumber is either 0 or 1
Mifare_A/B are two different const int values that have to be stored in the array

So I guess this is some kind of short if-clause?

micha

It is a short form of a if then else.

The if part is before the ?, the then part is up to the : and the else is after the :

Edit:
Please use code tags - the <> button under format on the right, (or bottom for a new post)

pn532_packetbuffer[2] = (keyNumber) ? MIFARE_CMD_AUTH_A : MIFARE_CMD_AUTH_B;
Last edited on
It's the tenary operator and kind of short for
1
2
3
4
if(keyNumber)
 pn532_packetbuffer[2] = MIFARE_CMD_AUTH_A
else
 pn532_packetbuffer[2] = MIFARE_CMD_AUTH_B;


Read this: http://www.cplusplus.com/forum/articles/14631/
And this: http://en.cppreference.com/w/cpp/language/operator_precedence
The important difference is that an arithmetic if results in an expression.
There are situations where only an expression would do. For example:

1
2
3
4
5
6
7
8
9
struct something
{
     explicit something( const char* its_name )
               : name( its_name && its_name[0] ? its_name : "anonymous" ) {}

     // ...

     private: const std::string name ;
};
Topic archived. No new replies allowed.