Counting Woes

October 18, 2013

In #learnprogramming on Freenode, someone came in with this question:

14:00 <cordell> I have a question about they way my C++ program works. here is the code. http://slexy.org/view/s2154xsHJT
14:00 <cordell> Specifically my question is, Why does if (array[k]=='o') statement not correctly output the answer and instead has to be written as if (array[k]='o' && array[k]=='o') ?

The paste has expired, but this is a short version of the problem code:

int main(void) {
    char array[] = "hello ooblong";
    int num_o = 0;
    for (size_t k = 0; k < sizeof(array); k++)
        if (array[k]='o' && array[k]=='o')
            num_o += array[k];
    printf("found %d o's\n", num_o);
    return 0;
}

The code tries to count the number of 'o's in the string. At first glance, the code obviously doesn't work because he's using array[k] = 'o' which overwrites the value. But then you read his question again: he's asking why the code doesn't work when he writes it as if (array[k]=='o') but works as written.

The first part is easy: he's adding array[k] to num_o instead of 1.

The second part is trickier and threw us for a loop. = has a very low precedence - lower than both && and ==. Fully parenthesized, the expression is array[k] = ('o' && (array[k] == 'o')) which evaluates to 1 when it's o and 0 otherwise. That value is cast to a char and written, then added to num_o.

15:26 <darkf> it makes me want to start writing broken-but-subtly-working code.