C introspection: can you verify the sizes of short int and long int by using the sizeof operator in portable C code?

Difficulty: Easy

Correct Answer: Correct

Explanation:


Introduction / Context:
Type sizes in C are implementation-defined and can vary across platforms and ABIs. The language provides the sizeof operator to query object sizes at compile time (and also usable in constant expressions). This question checks whether sizeof is the correct portable way to discover sizes for short int and long int.


Given Data / Assumptions:

  • C code compiled with a conforming compiler.
  • Types short int and long int exist with implementation-defined widths and alignment.
  • Need a reliable method to check sizes.


Concept / Approach:
sizeof(type) yields the size in bytes of any complete object type. It is evaluated at compile time for known types and is the standard mechanism for determining the storage size without resorting to non-portable tricks. This works equally for short, int, long, pointers, structures, and arrays (with caveats for flexible array members).


Step-by-Step Solution:

Use sizeof(short) and sizeof(long) in code.Optionally print results to confirm on the target environment.Rely on these values for memory allocation or serialization logic.


Verification / Alternative check:
Compare the values with limits macros from such as SHRT_MAX and LONG_MAX to ensure expectations match the ABI (e.g., LP64 vs LLP64).


Why Other Options Are Wrong:

Incorrect: denies a standard feature expressly designed for this task.Compiler pragmas, link-time checks, or inline assembly are unnecessary for discovering type sizes.


Common Pitfalls:
Assuming fixed sizes (e.g., long always 8 bytes). Always use sizeof for portability.


Final Answer:
Correct.

More Questions from Declarations and Initializations

Discussion & Comments

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