Can anyone explains this to me ?

Jan 25, 2019 at 1:39pm
Can anyone explains how this code works ?
Why we put a condition in an array ? how is this ?
I cant understand this !?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include<iostream>
#include<string>
using namespace std;
int main()
{
    std::string TorF[] = {"False", "True"};
    int a = 100;
    int b = 33;
    int c = 33;
    
    cout<<"a < b is "<<TorF[a<b];
    cout<<"\na > b is "<<TorF[a>b];
    cout<<"\na != b is "<<TorF[a!=b];
    cout<<"\nc >= b is "<<TorF[c>=b];
    cout<<"\nc <= b is "<<TorF[c<=b];    
    return 0;
}
Last edited on Jan 25, 2019 at 1:40pm
Jan 25, 2019 at 1:45pm
All the boolean operators yield a value 0 (for false) and 1 (for true).

These 0 or 1 values conveniently index your array of two elements.

It's as if you did
TorF[ a<b ? 1 : 0]
Jan 25, 2019 at 1:58pm
closed account (E0p9LyTq)
All the boolean operators yield a value 0 (for false) and 1 (for true).

The built-in logical and comparison operators return bool (true or false). That can be convertible to and from a numeric value.

https://en.cppreference.com/w/cpp/language/operator_logical
https://en.cppreference.com/w/cpp/language/operator_comparison
Jan 25, 2019 at 3:29pm
it is often faster in high performance code to have a little static array with your true and false results stored in it and to just type return (array[expression]) using this technique. if statements can (not always) cost you a bit more than necessary and this technique avoids the hit. The compiler is smart enough to do this exact thing FOR you MOST of the time when it optimizes, so you only have to do things this way once in a rare while if the compiler can't boil it down.
Topic archived. No new replies allowed.