Standard C expressions: which of the following operations is incorrect (produces a compile-time error) in ISO C?
-
Aint i = 35; i = i % 5;
-
Bshort int j = 255; j = j;
-
Clong int k = 365L; k = k;
-
Dfloat a = 3.14; a = a % 3;
-
Eunsigned int u = 7U; u = u + 1;
Answer
Correct Answer: float a = 3.14; a = a % 3;
Explanation
Introduction / Context:This question checks operator applicability across C types. The modulo operator % is defined only for integer operands. Using it with floating types is a common mistake that leads to compilation errors.
Given Data / Assumptions:
- Plain ISO C (not using fmod from math.h).
- Each statement is independent and syntactically complete.
- Implicit conversions follow the usual arithmetic conversions.
Concept / Approach:In C, % is the remainder operator for integer types only. For floating-point remainders, you must call the library function fmod or fmodf. Assignments to self (j = j; k = k;) are valid no-ops. Integer modulo and unsigned addition are also valid.
Step-by-Step Solution:Check each operation's operand types.(a) int % int → valid.(b) self-assignment on short → valid though pointless.(c) self-assignment on long → valid.(d) float % int → invalid; % not defined for float. Use a = fmod(a, 3.0); instead.(e) unsigned arithmetic → valid.
Verification / Alternative check:Try compiling (d): compilers report “invalid operands to binary %”. Replacing with fmod compiles and runs correctly.
Why Other Options Are Wrong:(a), (b), (c), (e) are legal C statements; only (d) violates operator rules.
Common Pitfalls:Assuming % behaves like mathematical modulo for real numbers; forgetting to include math.h and link with the math library when using fmod.
Final Answer:float a = 3.14; a = a % 3;