please i can't understand the while loop , why the loop show A two time and not one
char *s,*t;
s="ABC";
t="AA";
do {printf("A");}
while(*s++==*t++);
printf("%d %d",*s-*t);
please i can't understand the while loop , why the loop show A two time and not one
char *s,*t;
s="ABC";
t="AA";
do {printf("A");}
while(*s++==*t++);
printf("%d %d",*s-*t);
In your code
printf("%d %d",*s-*t);
invokes undefined behavior as you're not supplying enough argument to sate the supplied format specifiers.
why the loop show A two time and not one?
The first time after the do
, the print occurs unconditionally. Then the test occurs, and the condition is true (A == A). So the loop starts again, printing A
the second time. After that, the test occurs again, and the condition is false (D != A), so the loop terminates.
It prints 67
because (a) you are using the %d
decimal number output format, and (b), after the loop ends, *s == 'C'
and *t == '\0'
, and the difference of their ASCII values is 67
.
A do...while
loop always runs at least once. So on the first iteration, A
gets printed. In the condition s
points to the first character in its string (A
), and t
points to the first character in its string ( also A
). So it compares ('A'=='A')
which is true, then s
and t
are both incremented to point to the second character in each string (A
and B
respectively).
On the second iteration, another A
gets printed. In the condition it compares ('B'=='A')
which is false, then s
and t
are both incremented to point to the third character in each string. Since the t
string only contains two characters, t
actually points to the NULL byte at the end of the string.
In the printf
, it subtracts the value pointed to by s
(C
) by the value pointed to by t
(a NULL byte, which in your implementation is 0
). The ASCII value of C
is 67
, and 67 - 0 = 0
, so 67
is printed.