This is a program for converting letters to upper case.
Could anyone explain me what the condition of the for loop in the below program does?
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
int i;
char a[50];
gets(a);
for(i=0;a[i];i++)
a[i]=toupper(a[i]);
puts(a);
return 0;
}
gets()
will return a 0-terminated string, as all C strings should be. So if you entered "four", the actual contents added to a
will be those four letters followed by a 0
byte.
// as if you'd declared
char a[] = { 'f', 'o', 'u', 'r', 0 };
The loop tests each character to see that it's not 0
. When a[i]
is 0
, the condition fails, and the loop ends. It's simply looping over all of the actual characters in the string.
a[i]
evaluates to non-zero (true) for all the characters except the terminating null character. Hence, the loop breaks when a[i]
is the terminating null character.
By convention, strings in C have a zero byte at the end to indicate the end of the string. The for checks for this byte and stops executing when it is reached because all non-zero bytes in the string evaluate to true.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.