The code as written is using the parameter s
both as a pointer to a character, and as a character array indexed by i
. The for
loop is being used to iterate over the string, but the start of the string is being moved when a matching character is not found.
This is very clever code. Clever code is seldom a good thing.
"It works"
because the result of the expression s[i]==c ? i++ : s++
is not being used. Each branch performs an action, returning a value of a different type. Neither of those values is used in another expression.
I typically use for
loops for performing a defined number of iterations. In this instance I think a while
loop is more appropriate.
Using s
as a pointer
int frequency(char *s, char c) {
int count = 0;
while (*s != 0) {
if (*s == c) {
count++;
}
s++;
}
return count;
}
Using s
as a character array
int frequency(char s[], char c) {
int count = 0;
int current = 0;
while (s[current] != 0) {
if (s[current] == c) {
count++;
}
current++;
}
return count;
}