ProgrammingModerateAccenture · Capgemini pattern

What is printed?

What is printed?
printf("%d %d %d", strcmp("abc", "abd") < 0,
                  strcmp("ab", "abc") < 0,
                  strncmp("abcx", "abcy", 3) == 0);
  1. A. 0 0 1
  2. B. 1 1 1
  3. C. 1 0 1
  4. D. 1 1 0

Correct answer: B. 1 1 1

strcmp compares character by character: at index 2, 'c' < 'd', so the result is negative. "ab" vs "abc": at index 2 the first string has '\0', which is smaller than 'c', so it is negative too (a prefix sorts first). strncmp looks at only the first 3 characters, which are equal, so it returns 0.

More C Programming questions

Exams that ask this topic