Earlier quoted context omitted.
That is one of the most confusing pieces of C code I have seen lately. And it fails on an empty string: I would expect it to set b to 1 for an empty string, but it sets it to 0. Of course that could easily be fixed by setting b to 1 at the top. Also, code like this should always be put inside a function that returns a value, not just written inline. Making it a function allows simpler and more understandable code too…
You do realize it returns 1 for an empty string right? I mean it doesn't have any digits in it... What about adding a check of str[0] == 0 -> return 0 Also, giving char str[] will make it char* str. Which can be null. This may cause reading a random memory location (possibly segfault or use-after-free) edit: I get the comments but empty string still contains no digits. Given the regex would be ^[0-9]+ (+ instead of *…
Yes, and that was deliberate on my part, as it meets my expectation of what such a function should do in this edge case.
The problem statement was "Set boolean b to true if string s contains only characters in range '0'..'9', false otherwise."
To my mind, the question "is every character in the string a digit" should be equivalent to "are there any non-digits in the string" (with the answer inverted, of course).
Returning 0 (false) for the empty string makes those questions not equivalent. It makes the empty string a special case.
Of course the real problem is that the problem is under-specified. It should call out specifically what should happen for an empty string, because as illustrated here, this is something where reasonable people may disagree.
> Also giving char str[] will make it char* str. Which can be null. This may cause reading a random memory location (possibly segfault or use-after-free)
Well yes, of course. The point of my comment wasn't to write bullet-proof library-ready code, it was only to illustrate two things: code like this should always go in a function, and the entire task can be accomplished in a single pass through the string.
Thanks for keeping me on my toes!