Variables and types
In C, every variable has a type that never changes, and the type decides exactly how many bytes of memory the variable uses and how those bytes are read. Getting types right is the first step to correct C programs.
Declaring variables
#include <stdio.h>
int main(void) {
int count = 3; // whole number
double price = 19.99; // decimal number
char letter = 'Q'; // one character (single quotes)
bool in_stock = true; // true/false (built in since C23)
count = count + 2; // variables can change…
const int max = 10; // …unless they're const
printf("%d items at %.2f, letter %c, in stock: %d, max %d\n",
count, price, letter, in_stock, max);
return 0;
}5 items at 19.99, letter Q, in stock: 1, max 10
Declare a variable with its type, then its name. Always give it a starting value: a local variable that isn't initialised holds whatever bytes happened to be in that memory, and reading it is a bug:
#include <stdio.h>
int main(void) {
int total;
printf("total is %d\n", total);
return 0;
}main.c: In function ‘main’:
main.c:5:5: warning: ‘total’ is used uninitialized [-Wuninitialized]
5 | printf("total is %d\n", total);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.c:4:9: note: ‘total’ was declared here
4 | int total;
| ^~~~~
total is 2The compiler warned, but still built the program. That value could be anything: it changes between compilers, settings and runs.
Integer types
#include <stdio.h>
#include <limits.h>
int main(void) {
printf("char: %zu byte, %d to %d\n", sizeof(char), SCHAR_MIN, SCHAR_MAX);
printf("short: %zu bytes, %d to %d\n", sizeof(short), SHRT_MIN, SHRT_MAX);
printf("int: %zu bytes, %d to %d\n", sizeof(int), INT_MIN, INT_MAX);
printf("long: %zu bytes, %ld to %ld\n", sizeof(long), LONG_MIN, LONG_MAX);
printf("long long: %zu bytes\n", sizeof(long long));
printf("unsigned int: 0 to %u\n", UINT_MAX);
return 0;
}char: 1 byte, -128 to 127 short: 2 bytes, -32768 to 32767 int: 4 bytes, -2147483648 to 2147483647 long: 8 bytes, -9223372036854775808 to 9223372036854775807 long long: 8 bytes unsigned int: 0 to 4294967295
sizeof tells you how many bytes a type uses. The C standard only sets minimum sizes. int is 4 bytes on every common system today, but long is 8 bytes on Linux and macOS and 4 on Windows. When the exact size matters (file formats, network protocols), use the fixed-width types:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main(void) {
int8_t small = -100;
uint8_t byte = 255;
int32_t id = 2000000000;
uint64_t big = 18000000000000000000u;
size_t n = sizeof(big); // for sizes and counts
printf("%" PRId8 " %" PRIu8 " %" PRId32 " %" PRIu64 " %zu\n", small, byte, id, big, n);
return 0;
}-100 255 2000000000 18000000000000000000 8
| Type | Meaning |
|---|---|
int8_t … int64_t |
Signed, exactly 8 to 64 bits |
uint8_t … uint64_t |
Unsigned (no negatives), exactly 8 to 64 bits |
size_t |
The type of sizes and array indexes, printed with %zu |
The PRId32-style macros from <inttypes.h> give the right printf specifier on every system.
Overflow
Numbers have limits. Go past the top of an unsigned type and it wraps around to 0. Go past the top of a signed type and the behaviour is undefined: the compiler may assume it never happens, and anything can result.
#include <stdio.h>
#include <stdint.h>
#include <limits.h>
int main(void) {
uint8_t level = 250;
level = level + 10;
printf("uint8_t 250 + 10 = %d\n", level);
unsigned int u = 0;
u = u - 1;
printf("unsigned 0 - 1 = %u\n", u);
int big = INT_MAX;
long long safe = (long long)big + 1;
printf("INT_MAX + 1 as long long = %lld\n", safe);
return 0;
}uint8_t 250 + 10 = 4 unsigned 0 - 1 = 4294967295 INT_MAX + 1 as long long = 2147483648
To detect overflow, C23 added ckd_add, ckd_sub and ckd_mul in <stdckdint.h>. They return true if the result didn't fit:
#include <stdio.h>
#include <limits.h>
#include <stdckdint.h>
int main(void) {
int result;
if (ckd_add(&result, INT_MAX, 1)) {
printf("overflow detected, refusing to continue\n");
return 1;
}
printf("%d\n", result);
return 0;
}overflow detected, refusing to continue
Integer overflow bugs have caused real security holes and crashes. Use a type big enough for your values, and check when the input comes from outside.
Floating-point types
#include <stdio.h>
int main(void) {
float f = 0.1f;
double d = 0.1;
printf("float: %.20f (%zu bytes)\n", f, sizeof f);
printf("double: %.20f (%zu bytes)\n", d, sizeof d);
printf("0.1 + 0.2 = %.17f\n", 0.1 + 0.2);
printf("0.1 + 0.2 == 0.3? %s\n", (0.1 + 0.2 == 0.3) ? "yes" : "no");
return 0;
}float: 0.10000000149011611938 (4 bytes) double: 0.10000000000000000555 (8 bytes) 0.1 + 0.2 = 0.30000000000000004 0.1 + 0.2 == 0.3? no
- Use
doubleby default.floathas only about 7 correct digits. - Decimals like
0.1can't be stored exactly in binary, so never compare floating-point numbers with==. Check whether they're close:fabs(a - b) < 1e-9. - Money: store whole cents in an integer (
int64_t price_cents = 1999;), not adouble.
Characters are small numbers
A char is a 1-byte integer. Character literals like 'A' are just their ASCII codes:
#include <stdio.h>
#include <ctype.h>
int main(void) {
char c = 'A';
printf("%c is %d\n", c, c);
printf("%c\n", c + 2);
printf("'7' - '0' = %d\n", '7' - '0');
printf("%c %c %d\n", toupper('q'), tolower('Z'), isdigit('5') != 0);
return 0;
}A is 65 C '7' - '0' = 7 Q z 1
'7' - '0' turning a digit character into its value is a classic C trick. <ctype.h> has isdigit, isalpha, isspace, toupper and friends.
Converting between types
C converts automatically in mixed expressions, and you can convert explicitly with a cast, (type)value:
#include <stdio.h>
int main(void) {
int a = 7, b = 2;
printf("7 / 2 = %d\n", a / b);
printf("(double)7 / 2 = %.1f\n", (double)a / b);
double pi = 3.99;
int truncated = (int)pi;
printf("(int)3.99 = %d\n", truncated);
int minus = -1;
unsigned int ten = 10;
printf("-1 < 10u? %s\n", (minus < ten) ? "yes" : "no");
return 0;
}main.c: In function ‘main’:
main.c:12:37: warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsigned int’ [-Wsign-compare]
12 | printf("-1 < 10u? %s\n", (minus < ten) ? "yes" : "no");
| ^
7 / 2 = 3
(double)7 / 2 = 3.5
(int)3.99 = 3
-1 < 10u? no- Integer division drops the remainder. Cast one side to
doubleto get decimals. - Converting a decimal to an integer truncates (cuts off); it doesn't round. Use
round()from<math.h>to round. - Comparing signed and unsigned numbers converts the signed one to unsigned, so
-1becomes a huge number. That's why-1 < 10uis false.-Wextrawarns about it, as you saw.
Constants
#include <stdio.h>
#define MAX_USERS 100 // a preprocessor constant (text replacement)
constexpr double TAX = 0.18; // a C23 compile-time constant with a real type
enum { DAYS_IN_WEEK = 7 }; // an integer constant (works in every C version)
int main(void) {
const char *site = "Learn to Code"; // const: can't be changed after this
printf("%s: up to %d users, tax %.0f%%, %d days\n", site, MAX_USERS, TAX * 100, DAYS_IN_WEEK);
return 0;
}Learn to Code: up to 100 users, tax 18%, 7 days
Prefer constexpr or const over #define when you can: they have a type, and the compiler checks them.
auto and typeof (C23)
#include <stdio.h>
int main(void) {
auto total = 41 + 1; // the type (int) comes from the value
typeof(total) copy = total; // "the same type as total"
printf("%d %d %zu\n", total, copy, sizeof copy);
return 0;
}42 42 4
Useful inside macros and with long type names, but most C code still spells types out.
Practice
- Print the size of every basic type on your machine with
sizeof. - Store a price as cents in an
int64_tand print it as₹1,234.50-style text (price / 100andprice % 100). - Convert a temperature from Fahrenheit to Celsius:
(f - 32) * 5 / 9. Try it withintand withdoubleand compare. - Use
ckd_multo detect when multiplying twoints overflows.
1.What does 7 / 2 evaluate to in C when both are int?
2.What's the value of an uninitialised local int?
3.Which type should you use for money?
4.What does (int)9.99 give?