0
Hello, can someone explain this code to me?
Hello, I am trying to practice C++ and I have come across an interesting piece of code: int test(int x, int y) { const int n = 100; int val = abs(x - n); int val2 = abs(y - n); return val == val2 ? 0 : (val < val2 ? x : y); } Can someone explain to me how this section work: return val == val2 ? 0 : (val < val2 ? x : y);
2 Antworten
+ 3
Jibraeel Abdelwahhab
That's ternary operator which is a short of if and else statement
condition ? expression1 : expression2
Means if condition is true then expression1 will execute otherwise expression2 will execute
+ 2
It's same as :
if(val==val2){
return 0;
}
else {
if(val<val2){
return x;
} else {
return y;
}
}