Machine-translated by Google. Questions are authored in English.
Top

Discussion

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;
    }

 

  • A.Segmentation fault/code crash
  • B.Executable file name
  • C.Depends on the platform
  • D.Depends on the compiler

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.