I've been trying to get the arithmetic if operator to work but I just can't seem to do it. I'm new to C++ and still learning the basics but I'm just wondering if I'm using this operator correctly. It's supposed to return false if x < y. Is this the correct way to do it? I'm aware I can use an if else but I'm just wondering if I can also do it like this and if I can what I'm doing wrong.
#include <iostream>
using namespace std;
int x =0;
int y =1;
bool test()
{
return (x < y) ? true : false;
}
int main()
{
cout << test;
return 0;
}
These are two types of Arithmetic Operators in C. Binary. Unary.
These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).
7.1. The arithmetic operators for scalars in MATALB are: addition (+), subtraction (−), multiplication (*), division (/), and exponentiation (^). Vector and matrix calculations can also be organized in a simple way using these operators. For example, multiplication of two matrices A and B is expressed as A. *B.
Change
cout << test;
to
cout << test();
Otherwise you're not calling the function.
Also, the following:
return (x < y) ? true : false;
does the opposite of what you say you're trying to do ("return false if x < y").
The correct way is:
return (x < y) ? false : true;
Note that in this case the ternary operator is unnecessary, since you can simply do:
return !(x < y);
You state:
It suppose to return false if x < y
And you're trying to learn about the arithmetic if (ternary) operator, so ignore all the advice to eliminate it.
The first part after the ?
is what will be returned if the expression is true, and the second part after the :
is what will be returned if it is not true. Thus you have your return values reversed, and it should be:
return (x < y) ? false : true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With