ProgrammingHardProduct company OA

Assume ASCII. What is printed?

Assume ASCII. What is printed?
int my(const char *a, const char *b) {
    while (*a && *a == *b) { a++; b++; }
    return *a - *b;
}
int main(void) {
    printf("%d %d %d", my("abc", "abd"), my("ab", "abc"), my("b", "a"));
}
  1. A. -1 -100 1
  2. B. 0 -99 1
  3. C. -1 -1 1
  4. D. -1 -99 1

Correct answer: D. -1 -99 1

The loop stops at the first difference or at the end of a. 'c' − 'd' = −1. For "ab" vs "abc" it stops at a's '\0', and 0 − 'c' = −99. 'b' − 'a' = 1. Only the sign is guaranteed for the library strcmp, but this function returns the actual difference.

More C Programming questions

Exams that ask this topic