Programming in C: Understanding Expression Values

In C, expressions that involve comparison operators, such as (n == 0), (x != n + 1), or getchar() != EOF, evaluate to either 0 (false) or 1 (true). This follows the convention that any nonzero value is considered true, while zero represents false.

End of File (EOF) and Its Value

The symbolic constant EOF (End of File) is used to indicate the end of input when reading from a stream, commonly used with functions like getchar(), fgetc(), and scanf().

Although EOF is typically defined as -1, its exact value is implementation-dependent and may vary between different compilers or platforms. It is always defined in <stdio.h> and should be used as EOF rather than relying on its numeric value.

Character Constants and Their Integer Values

Character constants in C, such as 'A', ' ', and '0', are stored as integer values based on their ASCII codes. For example:

  • 'A' has an ASCII value of 65
  • ' ' (newline) has an ASCII value of 10
  • '0' has an ASCII value of 48

This allows characters to be used in arithmetic operations, such as calculating numeric values from character digits:

char digit = '5';
int number = digit - '0'; // Converts '5' to integer 5

Additional Notes on Expression Values

  • Logical expressions using &&, ||, and ! also return 0 or 1.
  • Bitwise operations (such as &, |, and ^) operate at the binary level and return results based on bitwise evaluation rather than 0 or 1.
  • Conditional expressions like n ? x : y return x if n is nonzero (true) and y if n is zero (false).

Understanding how expressions evaluate in C is fundamental for writing efficient and bug-free code, especially when dealing with conditional logic and input handling.