-1

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
ign0r
  • 13
  • 4
  • 2
    Please explain exactly what you don't understand about the code. Have you tried running your program one line at a time in a [debugger](https://stackoverflow.com/q/25385173/12149471), while monitoring the values of all variables? – Andreas Wenzel Feb 14 '22 at 10:38
  • 3
    This is the perfect opportunity to learn [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – the busybee Feb 14 '22 at 10:39
  • 2
    You may also rewrite that `for` as a `while`, and replace the ternary operator with `if`-`else`, which will make the code so much better readable. – the busybee Feb 14 '22 at 10:41

1 Answers1

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335