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 (argc--)
        printf("%s\n", argv[argc]);
        return 0;
    }

 

  • A.Compile time error
  • B.Executablefilename
  • C.Segmentation fault
  • D.Undefined

Answer: B

Correct answer: Executablefilename

With no arguments argc is 1. The condition while (argc--) tests the current value and then decrements, so the first test sees 1, which is true, and the body runs with argc now 0.

The call is therefore printf("%s\n", argv[0]), printing the program name. The next test sees 0, which is false, and the loop ends. The post-decrement is what makes the indexing come out right: the value tested and the index used differ by one.

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

Post your comment

Please log in or register to post a comment.