Search code examples
c++ci2c

How does this code work and what is it called


The code in question is "? something : something_else". Usually in the code below you can put either I2C_SLAVE or I2C_SLAVE_FORCE. But this code does something else. How does it work and what exactly does it do?

if(ioctl(state.i2c_bus_address, force ? I2C_SLAVE_FORCE : I2C_SLAVE, add) < 0)
{
    logger.fail("i2c select fail %d",add);
    return -1;
}

Solution

  • It's called the ternary conditional operator. It's like an if, but inline. Here's the format

    boolean ? result evaluated to if true : result evaluated to if false
    

    Here's an example:

    y = x>2 ? 12 : 5;
    

    If x is greater than 2, y will be 12, otherwise y will be 5.