I am having some difficulties in understanding the condition of the while
loop given below:
int main()
{
char s[]="Let's Get it Started";
int i=0;
while(s[i]!=0)
{
//do something
++i
}
}
I know that string is stored with the last character as \0
which has the ASCII value as 0
. In the while
loop, it is comparing the value of the particular characters of the array. So when it reaches \0
condition would be like
'\0' != 0 // I guess this is also true
So isn't this an infinite loop?
In C
, '\0'
has same value (and even type) as 0
. Both are int
s with 0
value.
So isn't this an infinite loop ?
So, no it is not an infinite loop because of assumption that \0
and 0
are different. But the loops may be infinited for other factors not in the scope of this question.
From C11 specs section 5.2.1/2 Character sets
A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string.