Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux c/c++ - weird if/else issue

Tags:

c++

c

linux

mysql

I'm querying a mysql table which then loops through the results.

One of the fields has a value of "0" in it, so when I try the following it doesn't work!

while ((row2 = mysql_fetch_row(resultset2)) != NULL) {
    if (row2[2] != "0") {
        // the field has a value of 0, but it's still executing the code here!
    } else {
        // should be executing this code
    }
}

I know C/C++ is very strict when it comes variables (unlink php), but I can't figure this one out. Anyone have any ideas why?

like image 789
Joe Avatar asked Nov 28 '25 09:11

Joe


2 Answers

You're comparing row2[2], a pointer to char, with a pointer to the constant char array "0".

Use strcmp(row2[2], "0") != 0 (C solution), std::string(row2[2]) != "0" (C++ solution), or atoi(row2[2]) != 0 if you know row2[2] is always the string representation of an integer (and cannot be a SQL NULL value).

like image 184
Fred Foo Avatar answered Nov 29 '25 22:11

Fred Foo


You cannot compare string literal like this :

if (row2[2] != "0") //wrong

Either you do this :

if (strcmp(row2[2], "0")) //correct 

Or this:

if (std::string(row2[2]) != "0") //correct

For this particular case, when there is only one character you can also do this:

if (row2[2][0] != '0') //correct  - not the single quote around 0!
like image 21
Nawaz Avatar answered Nov 29 '25 23:11

Nawaz