Code:int mystery2(const char *s) { int x; for (x = 0; *s!='\0'; s++) ++x; return x; }
i dont understand wats *s! = '\0' and ++x; for
Code:int mystery2(const char *s) { int x; for (x = 0; *s!='\0'; s++) ++x; return x; }
i dont understand wats *s! = '\0' and ++x; for
One compares something with zero, and the other increments a value.
You could just try calling it with a few strings, and observing the output you get.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
but why not use s != 0 instead using s != '\0'
They're effectively the same thing. However, the character null is in fact '\0'. See the single quotes? That means it's a single character. This single character here is what we call the null character.
Quzah.
Hope is the first step on the road to disappointment.
The function calculates the length of the string that s points to. *s means the current character in the string and '\0' is the null character with which all strings end. So the function checks for the end of the string and increments x and s by one. In the end, x holds the length of the string.
Nice hint.