Reputation: 85
I am new to programming, not getting the code below. This program checks if a character c
is in the string s
.
int is_in(char *s, char c){
while(*s){
if(*s==c) return 1;
else s++;
return 0;
}
The main thing confusing me is, how the while
loop will stop, as, I think s++
will go through all over the memory, after the end of string also. Can anyone explain this please? Please correct me if I am wrong.
Upvotes: 1
Views: 86
Reputation: 234635
The loop stops when *s
is 0, i.e. at the end of the NUL-terminated string.
The idiomatic way of modelling strings in C is to terminate them with 0. Note that if s
is not formed in this way, then the behaviour of your function is undefined.
Personally I'd prefer the function to be int is_in(const char *s, char c)
to signify to the caller that the function doesn't modify the string.
Upvotes: 3
Reputation: 21532
Your intuition that the pointer s
will continue to loop indefinitely would be correct were it not for two things:
'\0'
). This acts as a sentinel value for functions that process strings; this is necessary since when an array is passed to a function it decays to a pointer to its first element, losing length information.while(*s)
will be false when the null terminator is reached.In fact, while(*s) { loop-body; s++; }
is a well-known idiom in C for processing strings.
Upvotes: 1
Reputation: 1039
The string char *s
is supposed to end with terminating NUL
. The value of NUL
is zero. Zero is what *s
is supposed to "expand" to eventually.
Upvotes: 0