Good afternoon! I have some doubts about following code.
[1] What does the middle condition in the for loop mean? ; *p; and ; *sval; – reaching an end of input string? If yes, how is it determined?
[2] I do not understand that complicated for loop.
Let’s suppose that if condition is not satisfied *p == % so we go into switch right away. Now let’s consider opposite case, we enter every other char despite %, if is satisfied so we use continue and also go to switch after that. What’s the difference between those 2 cases then ?
I must be terribly wrong with sth, but I can’t find my mistake for over 2 hours now…
#include <stdarg.h>
/* minprintf: minimal printf with variable argument list */
void minprintf(char *fmt, ...)
{
va_list ap; /* points to each unnamed arg in turn */
char *p, *sval;
int ival;
double dval;
va_start(ap, fmt); /* make ap point to 1st unnamed arg */
for (p = fmt; *p; p++) { /* [1] */
if (*p != '%') {
putchar(*p);
continue; /* [2] */
}
switch (*++p) {
case 'd':
ival = va_arg(ap, int);
printf("%d", ival);
break;
case 'f':
dval = va_arg(ap, double);
printf("%f", dval);
break;
case 's':
for (sval = va_arg(ap, char *); *sval; sval++)
putchar(*sval);
break;
default:
putchar(*p);
break;
}
}
va_end(ap); /* clean up when done */
}
Help is greatly appreciated!
When we
continue, we just print the character, and skip the switch altogether. The loop goes through the format line looking for (1) a terminating zero, or (2) a percent sign.When the terminating zero is reached, the loop ends:
When a percent sign is reached, the following symbol is taken as a format character, and the next vararg is interpreted according to it.
There is a bug in this program – it produces a read past the end of the format string (an undefined behavior) when the percent symbol is the last character of the format string. Try this:
The simulated end-of-line marker
\0is skipped, and thebug!bug!bug!output is produced. The reason for this is an unconditional pre_increment ofpin the header of theswitchstatement. To fix this problem, add the following case to theswitch: