ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int parse(const char *s) {
    int sign = 1, n = 0;
    if (*s == '-') { sign = -1; s++; }
    while (*s >= '0' && *s <= '9') n = n * 10 + (*s++ - '0');
    return sign * n;
}
int main(void) { printf("%d %d", parse("-042x7"), parse("+5")); }
  1. A. -42 5
  2. B. 0 0
  3. C. -42 0
  4. D. -427 0

Correct answer: C. -42 0

The leading zero adds nothing and the loop stops at 'x', so the first is −42 (the 7 after x is never read). parse handles only '-', so for "+5" the loop sees '+' first, reads no digits and returns 0. The library atoi would accept the '+'.

More C Programming questions

Exams that ask this topic