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

Discussion

What will be the output of the following C code?

#include <stdio.h>
    int main()
    {
        char *str = "hello, world";
        char *str1 = "hello, world";
        if (strcmp(str, str1))
            printf("equal");
        else
            printf("unequal");
    }

 

  • A.equal
  • B.unequal
  • C.Compilation error
  • D.Depends on the compiler

Answer: B

Correct answer: unequal

This is the trap in strcmp: it returns 0 when the strings are equal, and 0 is false. The two strings here have the same contents, so the condition fails and the else branch runs, printing unequal. The test should be written if (strcmp(a, b) == 0).

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

Post your comment

Please log in or register to post a comment.