Search code examples
cstaticoperator-keywordconditional-operatorstorage-duration

Ternary operator in a for loop


So I have the following code:

#include <stdio.h>

int f(char *c)
{
    static int i=0;
    for (;*c;*c++=='a'?i--:i++);
    return i;
}
int main()
{
    for(int i=1; i<4; i++)
        printf("%d:%d\n", i, f("buba"));
    return 0;
}

I already know what is gonna be written in the output of the program, but my question is why? If you edit the string and make subtle changes, the output remains the same which is:

1:2
2:4
3:6

Solution

  • The static variable i declared in the function is initialized only once before the program startup. So its value is preserved between function calls.

    In this for loop

    for (;*c;*c++=='a'?i--:i++);
    

    the variable i is increase three times because there are three letters in the string literal before the letter 'a'

    "buba"
    ^   ^
    | 3 |
    

    and decreased one time. So in total it is increase by 2 in each call of the function when the string "buba" is passed.

    For example if you will call the function like

    f( "123456789a" )
    

    then the variable i within the function will be incremented by 8.