How does this code work and what is it called - c++

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;
}

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.

It's name is "conditional operator".
condition ? expression1 : expression2
If condition evaluates to true, then evaluate expression1, otherwise evaluate expression2.

Not sure if this is what you're after, but the statement ? if_true : if_false control flow is called the ternary operator.
The statement is evaluated. If it's true, the expression after the : is evaluated. Otherwise, the expression after the : is evaluated.

Related

Can someone explain the syntax behind this line of code? C++

My professor is having us change her functions to work for her assignment on Binary Search Trees. I know that this line she has assigns myHeight to whatever value being compared that is greater, but I have no idea how it's actually doing that.
int maxH = (hL > hR) ? hL : hR;
I want to use this in the future since it can save time writing code, but to do that I need to understand the syntax first. Thanks guys
This is the so called "conditional operator" in c++. It works as follows:
the expression before the ? is evaluated and converted to bool,
if it evaluates to true, the second operand is evaluated (i.e. hL in your example),
otherwise, the third operand (hR in your example) is evaluated.
The result is assigned to maxH.
See here for more detail (go down to the section "Conditional operator").
This is known as the conditional operator in C++.
"The conditional operator is an operator used in C and C++ (as well as other languages, such as C#). The ?: operator returns one of two values depending on the result of an expression.
Syntax
(expression 1) ? expression 2 : expression 3
If expression 1 evaluates to true, then expression 2 is evaluated.
If expression 1 evaluates to false, then expression 3 is evaluated instead.
Examples
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
In this example, the expression a > b is evaluated. If it evaluates to true then a is returned. If it evaluates to false, b is returned. Therefore, the line MAX(4, 12); evaluates to 12.
You can use this to pick which value to assign to a variable:
int foo = (bar > bash) ? bar : bash;
In this example, either 'bar' or 'bash' is assigned to 'foo', depending on which is bigger.
Or even which variable to assign a value to:
((bar > bash) ? bar : bash) = foo;
Here, 'foo' is assigned to 'bar' or 'bash', again depending on which is bigger."
https://cplusplus.com/articles/1AUq5Di1/
Using your teacher's example:
int maxH = (hL > hR) ? hL : hR;
This is equivalent to "if hL is greater than hR, then assign the value of hL to maxH, otherwise assign the value of hR to maxH."
The expression condition ? v1 : v2 returns v1 if condition is true, v2 otherwise.
int maxH = (hL > hR) ? hL : hR;
is equivalent to
int maxH;
if(hL > hR) maxH = hL;
else maxH = hR;
It's the conditional/ternary operator. It is used as an alternative to short if..else statements. Its syntax is as follows:
condition ? exprIfTrue : exprIfFalse
The condition before the (?) is evaluated as a bool. If it is true, exprIfTrue is executed. If it is false, exprIfFalse is executed. The (:) acts as the separator between the two conditions.
In your case, the condition evaluates if hL is greater than hR and assigns hL to integer max if it is true, or it assigns hR to integer max if it is false.
Note: Besides false, other false expressions could be null, NaN, 0, empty string (""), and undefined.

Checking container size in same "if" statement as reading from it

Let's say I have a vector of unknown length.
I want to check if there is a value at vector[3] that is equal to x.
I have to first check if the vector has a length of at least 4.
if(vector.length()>=4)
{
if(vector.at(3) == x)
// Do something
}
My question is: Is it correct to write the same code like this:
if(vector.length()>=4 && vector.at(3) == x)
// Do something
?
Yes, these are equivalent.
The logical AND operator && has what is referred to as short circuit behavior. If the left operand evaluates to false (i.e. 0) then the entire expression is false and the right operand is not evaluated.

Ternary operator with no condition

I found a section of code that shows the following:
int A = 4;
int Z;
Z = (A ? 55 : 3);
Why does the result for Z give 55?
You seem to have a common misconception about the fact that expressions in conditional statements (if, while, ...) and ternary operations must "look like" a condition, so they should contain a relational/equality/logical operator.
It's not like that. Commonly used relational/equality/... operators don't have any particular relationship with conditional statements/expressions; they can live on their own
bool foo = 5 > 4;
std::cout<<foo<<"\n"; // prints 1
and conditional statements/expressions don't care particularly for them
if(5) std::cout << "hello\n"; // prints hello
if/?/while/... just evaluate the expression, check if the result, converted to bool, is true or false, and act accordingly. If the expression doesn't "looks like" a condition is irrelevant, as long as the result can be converted to bool you can use it in a conditional.
Now, in this particular case A evaluates to 4, which is not zero, so when converted to bool is true, hence the ternary expression evaluates to its second expression, so 55.

How is this ternary conditional expression executed?

int x = 5,y = 10;
bool boolean = 0;
int k = (boolean ? ++x, ++y : --x, --y);
cout<<k;
When boolean is 0,it outputs 9, however when it is 1 it outputs 10.I know this is happening because of precedence but cannot exactly figure out how is it happening, please help me understand this.
NOTE:I know I can get the expected output if I use parenthesis,or better write a clean code,I am just using this to understand how compiler would evaluate expressions like these according to precedence.
, has lower precedence than ?:. Which means that the full parenthesising is:
int k = ((boolean ? (++x, ++y) : --x), --y);
As you can see, k is always initialised to the value of --y. It's just that if boolean is true, ++y happens before that.
When looking for the full parenthesis form of an expression, think of it as constructing the expression tree (where the lowest-precedence operator is at the root).
Find the lowest-precedence operator in an expression, and parenthesise its left-hand side argument and its right-hand side argument. Repeat recursively within the sub-expressions just parenthesised.
Due to the comma operator having the lowest operator precedence, your statement is actually equal to
k = (boolean ? (++x, ++y) : --x), --y;
That means when boolean is true you both increase and decrease y. The result of the ternary expression is thrown away in both cases and k is only assigned the result of --y.
It should be noted that this is not undefined behavior, as the comma operator introduces a sequence point.
To get the result you expect, you need to do
k = boolean ? (++x, ++y) : (--x, --y);
Note that the parentheses around ++x, ++y is strictly not needed, but it does make the expression clearer.
Given the above excellent answers, one should write instead:
if (boolean) {
++x;
++y;
} else {
--x;
--y;
}
int k = y;
Because then the code is more readable and clear in its intent. This will help anyone who has to maintain the code (including the original author!) without anyone having to waste time by asking SO questions or worrying about the precedence of , or ?: or what the logistics of assignment to such a complex expression are. Any modern compiler will optimize both this and the above to the same resulting code

Odd error using intrinsic typecasting in CUDA

I cannot figure out what the difference between the following pieces of code is:
int t = __double2int_rd(pos.x/params.cellSize.x*2.0)&1;
if( t ==0) {...}
and
if(__double2int_rd(pos.x/params.cellSize.x*2.0)&1 == 0) {...}
The second option never returns true, while the first behaves as expected.
Does anyone have any ideas?
The second expression first evaluates (1==0) whose result is always false. Then ANDs it with the result of the function __double2int_rd.
Therefore it actually evaluates:
if(__double2int_rd(pos.x/params.cellSize.x*2.0) & 0)
Which would always be false.
The equivalent of the first expression would be:
if((__double2int_rd(pos.x/params.cellSize.x*2.0) & 1) == 0)
Mind the brackets.
Its a good programming practice to add brackets if you are not sure about the order of evaluation of expressions.