Ternary Op

Just would like some quick clarification on the ternary operator. The book i have doesnt cover it. I just wanna see if a number is Neg or Pos and spit back negative or positive.


int vPos == 1 ? cout << "Positive" << endl; : cout << "Negative" << endl;

I get errors (obviously), im pretty sure my syntax is off or im just not using the operator correctly.
Remove the int and semicolon:

(vPos == 1)? (cout << "Positive" << endl) : (cout << "Negative" << endl);

Alternatively:

cout << ((vPos == 1)? "Positive" : "Negative") << endl;
you are comparing vPos but it does not contain any value and it's not created.
you need to declare it first, then initialize and finaly use.

1
2
3
4
5
6
7
8
int vPos; // create first
cin >> vPos; // then initialize

// finaly use it
vPos > 0 ? cout << "Positive" << endl : cout << "Negative" << endl;

// better approach with nested one:
vPos > 0 ? cout << "Positive" : vPos < 0 ? cout << "Negative" : cout << "zerro";
Thank you both i appriciate it!
Topic archived. No new replies allowed.