What will be the output of the following C code (run without any command line arguments)?
#include <stdio.h>
int main(int argc, char *argv[])
{
while (*argv != NULL)
printf("%s\n", *(argv++));
return 0;
}
Answer: B
Correct answer: Executable file name
Here the increment is in the body rather than the condition, and that makes the difference. The test examines *argv - argv[0], non-null - and the printf then prints that same element before advancing the pointer.
So the program name is printed. The next test finds argv[1], which with no arguments is the terminating null pointer, and the loop ends cleanly. Testing and printing the same element is what keeps this version correct where the companion is one out of step.
Please log in or register to report this question.