While statement problem

H

herrcho

#include <stdio.h>
int main()
{
char c[100];
int length=0;
printf("input string : ");
gets(c);
while(c[length++] != '\0');
printf("the length of input string is %d \n", length-1);
printf("the number of byte containing null character is %d",length);
printf("\n");
}

when i change the while statement to the following , it shows different
result . i don't know why..

while(c[length] != '\0')
length++;

What's the difference between them ?
 
J

Josh Sebastian

#include <stdio.h>
int main()
{
char c[100];
int length=0;
printf("input string : ");
gets(c);
while(c[length++] != '\0');
printf("the length of input string is %d \n", length-1);
printf("the number of byte containing null character is %d",length);
printf("\n");
}

when i change the while statement to the following , it shows different
result . i don't know why..

while(c[length] != '\0')
length++;

What's the difference between them ?

Think about it. The first one will increment length if the test succeeds
or fails; the second will increment length only if the test succeeds.

Josh
 
M

Mark McIntyre

while(c[length++] != '\0');
when i change the while statement to the following , it shows different
result . i don't know why..

while(c[length] != '\0')
length++;

What's the difference between them ?

they're different. Think the logic through

The first always post-increments length, even if c[length]==0, because
the length++ is part of the loop condition and is executed in each
pass.

The second ONLY post-increments length if c[length]!=0, because if
c[length]==0, the loop body is not entered.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,079
Messages
2,570,574
Members
47,206
Latest member
Zenden

Latest Threads

Top