Skip to study material
← Question index

QUESTION 42 · String Operations

Explain string comparison using strcmp and why == is unsuitable for contents.

5 marks

Answer in brief

strcmp compares two null-terminated strings lexicographically, examining their contents rather than comparing pointer values.

Working

  1. Compare corresponding bytes from the beginning.
  2. Continue while they are equal and not at the end.
  3. At the first difference, the unsigned character values determine the result’s sign.
  4. If both strings end together without a difference, return zero.

Example

strcmp("Code", "Code") returns zero. The sample therefore prints Equal. Comparing a string with a longer string that starts with the same prefix treats the shorter completed prefix as earlier, since its null terminator is compared at that position.

Why not ==?

For pointer expressions referring to strings, == compares pointer values. Two pointers can identify different arrays containing equal text. Conversely, sharing one pointer does not perform a character-by-character text comparison. Use strcmp when the question is whether the stored text is equal.

Character rules

strcmp is case-sensitive and is not a general dictionary-order comparison for every language or locale. The exact encoding influences byte values. Do not hard-code an expected difference such as -32; inspect only the sign. For these introductory examples, use ordinary byte strings with valid termination.

Complexity

The function stops at the first difference or a terminating position. It may finish in O(1) for a first-byte difference, and needs up to O(min(m, n) + 1) byte comparisons for lengths m and n. It needs no growing output array, giving O(1) auxiliary space in the usual analysis.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <string.h>

int main(void)
{
    char a[] = "Code", b[] = "Code";
    int result = strcmp(a, b);
    if (result == 0) { puts("Equal"); }
    else if (result < 0) { puts("First is earlier"); }
    else { puts("First is later"); }
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Equal

Related exam questions

Related questions in the string functions category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q7(b) · 8 marks

    Describe string library functions with syntax and an example program.

    Paper P01 · page 1
  • March/April 2023 · Q4(a) · 5 marks

    Explain strcat and strcpy with examples.

    Paper P02 · page 1

View this category in the exam question bank →