# What's wrong with my turnary ? statement?

• 03-21-2006
xmltorrent
What's wrong with my turnary ? statement?
Have a look at my code below.

Code:

```#include <iostream> #include <cstdlib> using namespace::std; struct node {         int data;         struct node* left;         struct node* right; }; void printInOrder(node* myNode); int countNodes(node* myNode); // a quick function to simulate a tree structure. struct node* getTree() {                 // allocate space for six nodes.         struct node* root = new (struct node);         struct node* two = new (struct node);         struct node* three = new (struct node);         struct node* four = new (struct node);         struct node* five = new (struct node);         struct node* six = new (struct node);         root->data  = 1;                 two->data  = 2;                 three->data = 3;                 four->data  = 4;                 five->data  = 5;                 six->data  = 6;           root->left = two;                 root->right = three;                 two->left = four;                 two->right = five;                 three->right = six;                 return root; } int main() {         node *tree = getTree();         printInOrder(tree);         cout << "This tree has " << countNodes(tree) << " nodes." << endl; } void printInOrder(node* myNode){         if(myNode != 0){                 printInOrder(myNode->left);                 cout << myNode->data << endl;                 printInOrder(myNode->right);         }        } int countNodes(node* myNode){         /*if(myNode != 0){                 return (1 + countNodes(myNode->left) + countNodes(myNode->right));                } else                 return 0;*/                 //this is the statement in question         myNode != 0 ? return(1 + countNode(myNode->left) + countNode(myNode->right)) : return 0; }```
I know the syntax is correct because I checked it against another program I have that uses the operator and it works but this doesn't for some reason. My compiler tells me that it expects a primary expression before the return statement.
• 03-21-2006
Daved
The return should go at the head of the statement, followed by the comparison and then the value to return if true and the value to return if false. It is not like an if statement where you execute a command if the boolean expression is true. Instead the ternary expression only evaluates to a value depending on the boolean comparison. So you put the return in front so that you return that value.
• 03-21-2006
xmltorrent
Thanks for the help.
• 03-22-2006
Salem
Since ?: is just and if/else for expressions, you may as well save some confusion by writing
Code:

```if ( myNode != 0 ) {   return(1 + countNode(myNode->left) + countNode(myNode->right)); } else {   return 0; }```