Variables
7 min · C
Store values in named, typed boxes called variables.
Enemy 1 of 5
Printing a number with %d
A variable in C is a named chunk of memory sized to hold one specific type of value. int is the type for whole numbers; you write the type, then a name you choose, then = and the value: int age = 36;. From then on, age stands in for the value 36 wherever you use it.
C decides each variable's type up front and never changes it — this is called static typing. That means the compiler knows exactly how much memory age needs and what operations make sense on it before your program ever runs, which is one reason C code, once compiled, runs so efficiently.
printf doesn't automatically know how to turn an int into text — you tell it using a format specifier. %d is a placeholder that means "insert an int here", and the actual variable is passed as a second argument after a comma: printf("%d\n", age);.
Getting the placeholder wrong for the type — say using %d for a string, or %s for a number — is a classic C bug. Because printf trusts you to pass the right type for each placeholder, mismatches don't always cause a clean error; sometimes they just print garbage. Get comfortable with %d for int now, and you'll add more specifiers (%s for strings, %f for decimals) as you need them.
Loading editor...