But what if the character you’re looking for is the first character in the array? Then it would be element 0. So you can’t use 0 as the “didn’t find it” flag. You’ll have to use -1 for that.
Be careful with lines like that. If that’s at local scope then k doesn’t get initialized like that. While C does allow you to use the comma and create more than one variable on a single line, it is generally better practice to do them one at a time.
Yes, that’s what the standard disclaimer is for and i quote myself:
“Something like that anyway”
That leaves it open for critique as you have done, and have done rather nicely. So nicely that i changed the code to reflect that. k1 should have been initialized to -1 as you noted, and it is an integer so if it is -1 it wont be confused with the possible byte 0xFF because as an int that will be decimal 255 not -1.
So chars 0x00 through 0xFF are possible, although the “Something like that” clause allows for other changes too in order to fit the need.
As far as initialization with int k1=-1; i’ve never had a problem but if you want to recommend that we do instead:
that’s fine with me
So just to recap, the code was changed to initialize k1 as -1 and the exit value checked to see if it is zero or above as ‘found’ and -1 as ‘not found’.
I’ll still be invoking the “Something like that” disclaimer however so feel free to check the new version over, or even come up with your own version
There may also be a much more obfuscated C code version that works but is hard to read that is similar to the OP’s original idea. Might be fun to look at some examples.