In C, what is the effect of a negative number in a field width specifier?

2008

In C, what is the effect of a negative number in a field width specifier?

Answer: C. the values are displayed left justifiedConcept: In C's printf-family functions, a field width specifies the minimum number of characters printed for a value, with the remaining space filled by…

  1. A.

    the values are displayed right justified

  2. B.

    the values are displayed centered

  3. C.

    the values are displayed left justified

  4. D.

    the values are displayed as negative numbers

Attempted by 2400 students.

Show answer & explanation

Correct answer: C

Concept: In C's printf-family functions, a field width specifies the minimum number of characters printed for a value, with the remaining space filled by padding. A positive width right-justifies the value by default (padding added on the left). A negative width — which can only arise when the width is supplied via the * width argument — is defined by the C standard to be interpreted as the - (left-justify) flag combined with the absolute value of that width: it forces left-justified output, with padding added on the right instead.

Application: Trace a concrete case:

  1. Consider printf("[%5d]", 7) — the width 5 is positive, so the default (right-justified) alignment applies: it prints [ 7].

  2. Now consider printf("[%*d]", -5, 7) — the width argument passed is -5, a negative number.

  3. Per the format-specifier rule, that negative sign is stripped off to get an actual width of 5, and the - (left-justify) flag is activated because the supplied width was negative.

  4. The output therefore becomes [7 ] — left-justified, with the padding spaces moved to the right of the value.

Cross-check: This matches the ISO C standard (WG14 N1570 §7.21.6.1) and the POSIX printf specification, both of which state that a negative width argument is taken as the - flag with a positive width. It also rules out the other options: printf's format specifiers have no centering capability at all (ruling out center-alignment), and the field width never changes the sign of the printed value — only its alignment and padding (ruling out the "displayed as negative numbers" option).

Result: A negative field width specifier causes the value to be displayed left-justified.

Explore the full course: Iocl Engineers Officers Grade A Paper 2

Loading lesson…