Diagnose the conditional expression and returns: what does this program do? #include<stdio.h> int check (int, int); int main() { int c; c = check(10, 20); printf("c=%d ", c); return 0; } int check(int i, int j) { int *p, *q; p = &i; q = &j; i >= 45 ? return(*p) : return(*q); }

Difficulty: Easy

Correct Answer: Compile error

Explanation:


Introduction / Context:
This problem centers on correct use of the conditional (ternary) operator and the return statement in C. It highlights a syntactic misuse that leads to a compilation error.



Given Data / Assumptions:

  • Two local integers i and j with pointers p and q referencing them.
  • The function attempts: i >= 45 ? return(*p) : return(*q);
  • Standard C syntax rules apply.


Concept / Approach:
The ternary operator has the form condition ? expr1 : expr2. Both expr1 and expr2 must be expressions, not statements. return is a statement and cannot appear directly as an operand of the ternary operator.



Step-by-Step Solution:
The compiler parses the conditional operator.It encounters return(*p) where an expression is required.This violates syntax rules, causing a compile-time error.The correct code would be either:1) return (i >= 45 ? *p : *q);2) Use an if/else with separate return statements.



Verification / Alternative check:
Refactor as shown and recompile; the function will then return 20 for inputs (10, 20) because i >= 45 is false.



Why Other Options Are Wrong:
Options A/B/C suggest a valid return value, but the program never compiles successfully as written. “Undefined behavior” implies a runtime issue, but the code fails earlier at compilation.



Common Pitfalls:
Forgetting that the ternary operator expects expressions, not statements; attempting to abbreviate if/else syntax too aggressively.



Final Answer:
Compile error

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion