Variables, Data Types & Arithmetic – C
int, double, char, bool, sizeof, constants and the pitfalls of integer division.
C is statically typed: every variable has a fixed type that you specify when declaring it. The most important basic types are int (integer), double/float (floating-point number), char (a single character, technically a small number) and bool (from <stdbool.h>).
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int alter = 36;
double groesse = 1.68;
char buchstabe = 'A';
bool aktiv = true;
printf("%d %.2f %c %d\n", alter, groesse, buchstabe, aktiv);
printf("int: %zu, double: %zu, char: %zu bytes\n",
sizeof(int), sizeof(double), sizeof(char));
return 0;
}The sizeof operator returns the size in bytes (type size_t, format %zu). Sizes depend on the platform: int is usually 4 bytes, long is 4 or 8 depending on the system. If you need fixed sizes, use the types from <stdint.h>:
#include <stdio.h>
#include <limits.h>
#include <stdint.h>
int main(void) {
printf("int: %d to %d\n", INT_MIN, INT_MAX);
uint8_t klein = 200; // exactly 8 bits, unsigned (0..255)
int32_t genau = -5; // exactly 32 bits, signed
unsigned int u = 42u;
const double PI = 3.14159; // constant: cannot be changed
printf("%d %d %u %.2f\n", klein, genau, u, PI);
return 0;
}In a division, the type of the operands matters: two integers give an integer division (the fractional part is dropped, rounding toward 0). To get a floating-point result, at least one operand must be a double – a cast does that.
#include <stdio.h>
int main(void) {
printf("%d\n", 7 / 2); // 3 (integer division)
printf("%.1f\n", 7 / 2.0); // 3.5
printf("%.1f\n", (double)7 / 2); // 3.5 (cast BEFORE the division)
printf("%d %d\n", -7 / 2, -7 % 2);// -3 -1 (remainder has the sign of the dividend)
double falsch = 7 / 2; // integer first: 3, then converted to 3.0
printf("%.1f\n", falsch);
return 0;
}int x; printf("%d", x); reads garbage (undefined behavior). Initialize every variable at its declaration.char is a numeric type: 'A' is 65, 'A' + 1 is 66 ('B'). That is why c - '0' works to convert a digit into its numeric value.