i am working in embedded c for last some month and till now i have come across simple for loops like:
for(i=0;i<10;i++)
but now i came across a new type of for loop which is:
for(t=0; string[t]; ++t)
can anyone please tell me how this loop works.
The sample code is:
#include <stdio.h>
#include <ctype.h>
void print_upper(char *string);
int main(void)
{
char s[80];
printf("Enter a string: ");
gets(s);
print_upper(s);
printf(''\ns is now uppercase: %s", s);
return 0;
}
/* Print a string in uppercase. */
void print_upper(char *string)
{
register int t;
for(t=0; string[t]; ++t)
{
string[t] = toupper(string[t]);
putchar(string[t]);
}
}
If the string is null-terminated, then the last character will be a null. This evaluates as false. The middle clause of the for syntax is a boolean expression. If it is true, the loop continues, if it is false, the loop terminates. The loop indexes character
tof the string, and incrementst, meaning that it tests each character in turn to see if it is ‘true’.This syntax would therefore loop over every character in the string and stop at the end.