Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ arithmetic if operator

Tags:

c++

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;
}
like image 705
Henning Joubert Avatar asked Nov 02 '11 14:11

Henning Joubert


People also ask

What is the operator arithmetic in C?

These are two types of Arithmetic Operators in C. Binary. Unary.

What are the 5 arithmetic operators?

These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).

How do you write an arithmetic operator?

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.


2 Answers

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);
like image 119
NPE Avatar answered Sep 23 '22 16:09

NPE


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;
like image 23
Mark Ransom Avatar answered Sep 22 '22 16:09

Mark Ransom