What would be the output of the following program, if run from the command…

2009

What would be the output of the following program, if run from the command line as “myprog 1 2 3”?

main (int argc, char *argv[])
{
  int i;
  i = argv[1] + argv[2] + argv[3];
  printf("%d", i);
}

Answer: C. ErrorIn C, the + operator is defined only between two arithmetic operands (such as int + int) or between a pointer and an integer (pointer + int gives an offset…

  1. A.

    123

  2. B.

    6

  3. C.

    Error

  4. D.

    “123”

Attempted by 28 students.

Show answer & explanation

Correct answer: C

In C, the + operator is defined only between two arithmetic operands (such as int + int) or between a pointer and an integer (pointer + int gives an offset pointer). The language does not define addition between two pointer operands — only pointer minus pointer is permitted, to compute the distance between two addresses. Applying + directly between two pointers is a constraint violation on that operator's operand types, for which the C standard requires the compiler to produce at least a diagnostic message; the code is therefore not valid strictly-conforming C and has no standard-defined output.

  1. When the program is invoked as “myprog 1 2 3”, argc is 4 and argv holds four character-pointer entries: argv[0] = “myprog”, argv[1] = “1”, argv[2] = “2”, argv[3] = “3” — so argv[1], argv[2], and argv[3] are each of type char*, not int.

  2. The statement i = argv[1] + argv[2] + argv[3]; therefore adds three pointer operands together: first argv[1] + argv[2], and then that intermediate result + argv[3].

  3. Both additions are pointer + pointer operations, a combination the addition operator's operand rules do not define (only pointer + integer, or integer + pointer, is defined).

  4. Because of this operand-type constraint violation, the C standard requires the compiler to issue a diagnostic message rather than silently accept the code as valid; the program is not standard-defined, so no reliable numeric value or string is guaranteed to reach printf and be produced at the command line.

This can be checked against what would actually compile: converting each argument first — i = atoi(argv[1]) + atoi(argv[2]) + atoi(argv[3]); — is valid integer addition and would give 6; separately copying and joining the characters of argv[1], argv[2], and argv[3] into a new buffer would give the text 123. The given program does neither conversion nor concatenation; it applies + directly to the three char* values, which is the operand-type violation described above.

Explore the full course: Nta Ugc Net Paper 2

Loading lesson…