Boardy
Boardy

Reputation: 36205

Ternary operator is always false

I am working on a project within C code and trying to use a ternary if statement but its always returning false and I don't understand why.

The ternary if statement is:

(reportParameterArray[P_TARGET] == '\0') ? reportParameterArray[P_TARGET] : "HELLO"

What I am trying to do is if reportParameterArray[P_TARGET] doesn't equal to \0 then it should output the actual value otherwise it prints hello. But at the moment it always prints HELLO.

When I debug I can see that the value is \0 so it should print "HELLO" but when there is an actual value it still prints HELLO and not the actual value of reportParameterArray[P_TARGET].

reportParameterArray[P_TARGET] is of type char**

Thanks for any help you can provide.

Upvotes: 0

Views: 1466

Answers (4)

peko
peko

Reputation: 11335

You should check for

(reportParameterArray[P_TARGET] == NULL)

because with

(reportParameterArray[P_TARGET] == '\0') 

you are comparing a char pointer to a char.

(*reportParameterArray[P_TARGET] == '\0')

is actually OK - '\0' is an integer value of zero, and in this context is evaluated as a null pointer constant, but if you mean NULL, just say NULL

Upvotes: 2

Imre Kerr
Imre Kerr

Reputation: 2428

As the other answers said, your conditional is backwards. But you're also comparing a char* to a char. You want to check the first character in the string, like so:

(reportParameterArray[P_TARGET][0] != '\0') ? reportParameterArray[P_TARGET] : "HELLO"

This is of course assuming you want to check for an empty string, and not a string that doesn't exist.

Upvotes: 2

Brian Agnew
Brian Agnew

Reputation: 272247

The ternary operation takes the form

condition ? when true : when false;

e.g

(var == 2) ? "Var equals 2!" : "Var doesn't equal 2!";

Hence you have your condition backwards.

Upvotes: 3

svk
svk

Reputation: 5919

Your ternary operator expression is backwards. You mean:

(reportParameterArray[P_TARGET] != '\0') ? reportParameterArray[P_TARGET] : "HELLO"

Or alternately:

(reportParameterArray[P_TARGET] == '\0') ? "HELLO" : reportParameterArray[P_TARGET]

Upvotes: 1

Related Questions