-5

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);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

4 Answers4

1

In your code

printf("%d %d",*s-*t);

invokes undefined behavior as you're not supplying enough argument to sate the supplied format specifiers.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

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.

donjuedo
  • 2,475
  • 18
  • 28
1

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.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

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.

dbush
  • 205,898
  • 23
  • 218
  • 273