Store a value with the right type
A variable names a region of storage. Its type controls which values it can represent and which operations make sense. Choose a type for the data rather than copying every value into an int. This lesson assumes you can build a program containing main.
Declarations and initialization
int students = 42;
double average = 78.5;
char grade = 'B';The first line declares an integer and gives it an initial value. A declaration such as int students; inside a function does not initialize the object. Reading that indeterminate value can produce undefined behavior. Initialize local variables before use.
char represents a character-sized integer type; a character constant uses single quotes. A string such as "B" is different: it is an array containing B and a terminating null character. For real-number calculations, double usually offers more precision than float. Floating-point values are approximations, so do not assume that every decimal fraction is represented exactly.
Inspect your own implementation
#include
#include
int main(void) {
int count = 42;
double mean = 78.5;
char grade = 'B';
printf("%d %.1f %c\n", count, mean, grade);
printf("int uses %zu C bytes\n", sizeof(int));
printf("bits per byte: %d\n", CHAR_BIT);
return 0;
} The first output line is 42 78.5 B. The size of int and the number of bits per byte are properties of the implementation; do not hard-code an expected size of four. sizeof returns size_t, which is printed with %zu.
Conversions that change an answer
5 / 2 is integer division and produces 2. 5.0 / 2 produces a floating-point result of 2.5. Assigning the result of 5 / 2 to double later cannot recover the discarded fraction. Convert an operand before division: (double)total / count, after checking count is nonzero.
Unsigned types cannot represent negative values. Mixing signed and unsigned arithmetic can produce unexpected comparisons. Signed overflow is undefined behavior; unsigned arithmetic wraps modulo one more than the maximum value. Neither is a reason to ignore range checks.
Practice and self-check
- Represent a student count, a temperature and a letter grade. Suggested types: int, double and char.
- Predict
double x = 7 / 2;. Answer: 3.0; both operands were integers. - Print sizeof(char). Answer: always 1 C byte, which does not by itself guarantee eight bits.
- Try assigning 4.9 to an int. The fractional part is discarded when the value is representable; choose a floating type if the fraction matters.
हिन्दी संकेत: variable को पढ़ने से पहले value दें। Type, range और division के operands देखकर ही result का अनुमान लगाएं।