C#.NET — Understand arithmetic promotions and overflow behavior. Given: short s1 = 20; short s2 = 400; int a; a = s1 * s2; What happens?

C# Programming Datatypes Difficulty: Easy
Choose an option
  • A
    A value 8000 will be assigned to a.
  • B
    A negative value will be assigned to a.
  • C
    If the result exceeds range, it wraps around automatically.
  • D
    A compile-time error is reported because widening conversion cannot take place.
  • E
    An overflow error is reported since the product exceeds the range of Short.

Answer

Correct Answer: A value 8000 will be assigned to a.

Explanation

Introduction / Context:This checks your understanding of integral promotion and arithmetic in C#. Even though operands are shorts, arithmetic is performed using int unless explicitly controlled.

Given Data / Assumptions:

  • s1 = 20 (short), s2 = 400 (short).
  • Expression: s1 * s2 assigned to int a.
  • Unchecked context assumed (default), but the result 8000 fits in int.

Concept / Approach:In C#, short and byte are promoted to int for arithmetic. Thus s1 * s2 is computed as int * int → int, producing 8000. No overflow occurs because 8000 is well within int range.

Step-by-Step Solution:

Promote s1, s2 to int. Compute 20 * 400 = 8000 (int). Assign to a (int) without any cast or error.

Verification / Alternative check:Change a to short and assign a = (short)(s1 * s2). Then a remains 8000 because 8000 fits in short as well; no overflow in either case here.

Why Other Options Are Wrong:No wraparound or negative result occurs; there is no widening error; and “overflow due to Short” is irrelevant because the computation is done in int.

Common Pitfalls:Assuming that arithmetic stays in the smaller operand type or that promotions cause overflow automatically.

Final Answer:A value 8000 will be assigned to a.

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