Reputation:
for (i = 0; isspace(s[i]); i++) { ... }
The above for
loop is the part of the program for converting a string to an integer in K&R on page 61.
There's no condition check in that for
loop. How does it work?
Upvotes: 1
Views: 95
Reputation: 309
isspace(s[i])
is the condition, since it returns a zero value for 'false' (i.e. the provided character is not a space character), and non-zero values for 'true'. In this case, only one space character exists, but in other functions such as isalpha
or isalphanum
, non-zero values mean different things like 1 means it is an upper-case letter (so it is an alphabetical character), or 2 means it is a lower-case letter) and so on (I may have mixed those numbers up :/).
In otherwords, the for
loop is treating this function as returning a boolean value, like most other expressions, meaning it treats zero-values as false
, and non-zero as true
.
Upvotes: 1
Reputation:
Yes If the for loop have without condition checking , the for loop will exit whenever the condition part will be zero
For example
` int i ;
for (i=0; 7-i; i++)
printf("hello world \n");
getch();
return 0;
}`
See the above program the 'i' minus the seven each time . and the loop will exit whenever the value of condition part will be zero (ie 7-7) .
Upvotes: 0
Reputation: 44828
First of all, you're going to get out of bounds, which is gonna give you a segfault. You're just increasing i
, but not checking whether it's still in the bounds or not. For example, what if s
would be equal to " "
? isspace(i[0])
will return a non-zero value (treated as true) and the loop will continue and will try to access the second (non-existent!) value of s
. You'd better add another tiny check: for (i = 0; (i<SIZE_OF_S) && isspace(s[i]); i++) { ... }
Let's now talk about the missing condition. No, it's not missing, it's here: isspace(s[i])
. This function checks whether s[i]
is considered space or not. It returns a non-zero value if yes, and 0
otherwise (docs). So, it is the missing condition, just in a slightly different form (maybe you're used to different comparisons, but there exist a lot more ways.
Upvotes: 0
Reputation: 4034
The loop terminates whenever the condition expression evaluates to 0. If for instance you see an expression like i < 3
, you can think of it as (i < 3) != 0
. So in this case, it's isspace(s[i]) != 0
meaning it terminates at the first character that is not a space.
Upvotes: 2