Programming in C: Important Points on Data Types

Understanding int and short

The size of int in C can be either 16-bit or 32-bit, depending on the machine architecture and compiler implementation. Generally:

  • On older 16-bit systems, int is 16 bits.
  • On modern 32-bit and 64-bit systems, int is 32 bits.
  • short is often 16 bits, though it can vary based on the compiler.

Signed and Unsigned Characters

The signed and unsigned qualifiers can be applied to char. However, whether plain char (i.e., without signed or unsigned specified) is signed or unsigned is machine-dependent. This can affect operations involving negative values. For portability, it’s best to explicitly declare signed char or unsigned char when working with character data.

Implicit Type Conversions

When assigning between different data types, implicit conversions occur:

  • If x is float and i is int, the assignment x = i; converts i to float.
  • Conversely, i = x; truncates x to an integer, losing the decimal portion.

Understanding these implicit conversions is crucial to avoid unexpected results.

Specifying Types Correctly in Expressions

When writing expressions, you must ensure that constant arithmetic follows correct type rules. Consider the following example:

(float) a = (b - 18) * 7 / 9;

In this case, the constant division 7 / 9 is treated as integer division, which results in 0 (since both operands are integers). To ensure correct floating-point computation, use:

(float) a = (b - 18) * 7.0 / 9.0;

or explicitly cast part of the expression:

(float) a = (float)(b - 18) * 7 / 9;

This prevents unintended truncation and ensures proper floating-point arithmetic.

Integer Ranges Depend on Machine Architecture

The range of int and float types is machine-dependent. For example, on a system where int is 16 bits:

  • The total number of values is 2^16 = 65536.
  • Signed integers range from -32,768 to 32,767 (65536 / 2).

On a 32-bit system, the signed integer range extends to -2,147,483,648 to 2,147,483,647 (2^31).

Conditional Expressions and Type Conversion

Consider the following expression:

(n > 0) ? f : n;

where f is float and n is int. According to C’s type promotion rules, the entire expression evaluates to float regardless of the condition because float has a higher rank than int. This implicit promotion ensures consistency in expression evaluation.

Additional Considerations

  • Use sizeof() to determine data type sizes on different systems.
  • Be mindful of type conversions in mixed arithmetic operations.
  • Explicit casting is preferred when converting between types to avoid surprises.
  • Understand integer overflows, especially when working with large values.

By following these principles, you can write more predictable and portable C code!