ProgrammingVery hardGATE CS

What is printed? (sizet is an unsigned type.)

What is printed? (size_t is an unsigned type.)
#include <stdio.h>
#include <string.h>
int main(void) {
    char s[] = "ab", t[] = "abcd";
    if (strlen(s) - strlen(t) < 0) puts("A");
    else puts("B");
    printf("%d", (int)strlen(s) - (int)strlen(t) < 0);
    return 0;
}
  1. A. B then 1
  2. B. B then 0
  3. C. A then 1
  4. D. A then 0

Correct answer: A. B then 1

strlen returns the unsigned size_t, so 2 - 4 wraps to a huge positive value and the < 0 test is always false, printing B. Casting to int first gives -2 < 0, which is 1.

More C Programming questions

Exams that ask this topic