Consider the following C program. What will it print when run?
#include <stdio.h> int check(int x) { if (x > 0) return 1; else if (x == 0) return 0; else return -1; } int main() { int result = check(-5); if (result == 1) printf("Positive\n"); else if (result == 0) printf("Zero\n"); else printf("Negative\n"); return 0; }
Look at the return values of the check function and what main does with them.
The function check returns -1 when the input is less than 0. Since -5 is less than 0, result is -1, so the program prints "Negative".
What value does the function process return when called with process(10)?
int process(int n) { if (n % 2 == 0) return 0; else return 1; }
Check if 10 is even or odd.
Since 10 is even, n % 2 == 0 is true, so the function returns 0.
What error will this C code produce when compiled?
int check(int x) { if (x > 0) return 1; else if (x == 0) return 0; // Missing return for negative x } int main() { int r = check(-1); return 0; }
Think about what happens if x is negative.
The function check does not return a value if x < 0. This causes a compiler warning that control reaches the end of a non-void function without returning a value.
How many distinct return codes can the function status produce?
int status(int code) { switch(code) { case 0: return 100; case 1: return 200; case 2: return 300; default: return 400; } }
Count all unique return values possible from the switch cases including default.
The function returns 100, 200, 300, or 400 depending on the input. That is 4 distinct return codes.
Which option correctly describes the best practice for using return codes in C functions to indicate success or failure?
Think about common C conventions for return codes.
In C, the common convention is to return 0 to indicate success and non-zero values to indicate different error types. This allows easy checking of success or failure.