SITERAW

Variables in C

We're now diving into a chapter that is oh-so important for everything that comes next β€” a chapter you absolutely shouldn't skip under any circumstances (in other words, now's not the time to stare off into space watching flies buzz around πŸ˜‰).

Previously, on This Programming Adventure:

In the last chapter, you learned how to create a new console project using your IDE (whether it's Visual Studio, VS Code, or another). I explained why starting off with fancy graphical windows is way too complicated for beginners (and don't even get me started on building a networked 3D video game 😜). So, for now, we'll stick with a good old-fashioned console that's kind of reminiscent of DOS. Once you're more confident, we'll tackle cooler stuff.

You already know how to display text on the screen. Awesome. I get it β€” you might be thinking this isn't super exciting yet, but that's only because you haven't met programming's best friend: the variable.

Ah yes, variables. Let's talk about those! You can't escape them β€” every programming language has them, and C is no exception.

Wait, so what exactly is a variable?

I've got this whole chapter to explain it. Without spoiling the surprise, let's just say you're about to learn how to make a computer remember numbers. We're going to learn how to store data in memory.

But first, I want us to take a little detour into how your computer's memory works. What is memory, anyway? How many types of memory does a computer actually have?

This might seem a bit basic to some of you, but keep in mind that not everyone here knows what memory is ;)

A World of Memory

What we're going to cover in this chapter is closely tied to how your computer's memory works.

Every normal human being has memory. Well, so does a computer... with one key difference: a computer has multiple kinds of memory!

Why on Earth would a computer need different types of memory? Wouldn't just one be enough?

Nope! The issue is that we need memory that's both fast (to access information quickly) and large (to store a lot). But here's the kicker: to this day, we've never managed to build memory that's both super fast and super spacious. More precisely, fast memory is expensive β€” so we only use small amounts of it.

To get around that, computers are built with a mix of very fast (but small) memory, and slower (but big) memory. Makes sense so far, right? πŸ˜„

The Different Types of Memory

To give you a better picture, here are the main types of memory in a computer, from fastest to slowest:

  • Registers – ultra-fast memory built right into the processor.
  • Cache memory – acts as a bridge between the registers and RAM.
  • RAM (Random Access Memory) – this is the type we'll use most often.
  • Hard Drive – you probably know this one; it's where files are saved.

As I mentioned, this list is ordered from fastest (registers) to slowest (hard drive). And as you probably figured out by now, the faster the memory, the smaller it is β€” and vice versa.

Registers can only hold a few numbers, while your hard drive can store massive files.

When I say a memory is β€œslow,” I mean in computer terms. For a human, 8 milliseconds is nothing β€” but for a computer, it's an eternity when accessing a hard drive!

So what should you take away from all this?

Well, I just wanted to give you some context. From now on, we'll mostly be working with RAM in our code. Later on, we'll learn how to read and write to the hard drive (to handle files), but not right away. As for cache and registers β€” don't worry about them. Your computer takes care of that on its own.

In very low-level languages like Assembly (aka β€œASM”), you do mess with registers directly. I've done it, and trust me β€” doing something as simple as a multiplication feels like running an obstacle course! Luckily, in C (and most other languages), it's much simpler.

Here's one last thing that's super important: only the hard drive permanently remembers the information it stores. All other types of memory (registers, cache, and RAM) are temporary β€” when you turn off your computer, they're wiped clean!

Thankfully, when you power it back on, your hard drive is still there to remind your computer who it is πŸ˜„

RAM is often visualized as two β€œcolumns”:

  • Addresses – an address is a number that helps your computer locate something in memory. Memory starts at address 0 (the very beginning), and goes all the way up to 3,441,765,900,127 and beyond... Okay, I don't actually know how many addresses there are in RAM β€” I just know it's a lot.
  • It also depends on how much RAM your computer has. The more RAM, the more addresses, and the more you can store ;)
  • Values – each address can store one value (a number). Your computer stores these numbers in RAM to remember them later. But remember: one number per address!

So RAM can only store numbers.

But wait β€” what about words?

Good question. Here's the thing: even letters are just numbers to a computer! A sentence is really just a sequence of numbers!

There's a table that links numbers to letters. It might say, for example, that the number 88 corresponds to the letter X. I won't go into details now β€” we'll cover that later on in the course.

Back to our diagram. It's actually really simple: if your computer wants to remember the number 5 (maybe the number of lives a player has left), it puts that 5 somewhere in memory where there's space, and notes the address (say, 3,062,199,901).

Later, when it wants to know that number again, it checks memory cell #3,062,199,901 and finds... 5!

That's basically how it all works. Sure, it might seem a little abstract right now (why store a number if you just have to remember the address instead?), but don't worry β€” it's all going to start making sense very soon in this chapter. Promise! 😊

Declaring variables in C

Believe me, that little intro on memory will come in handier than you think. Now that you've got the basics, we can get back to programming :D

So, what exactly is a variable?

Well, it's just a little piece of temporary information stored in RAM. That's it.

We call it a "variable" because it's a value that can change while the program is running. For instance, our number 5 from earlier (the number of lives left for the player) will probably go down over time. If it hits 0, we'll know the player lost.

You'll soon see that our programs are packed with variables. You'll find them everywhere, in every flavor.

In C, a variable is made of two things:

  • It has a value: the number it holds, like 5.
  • It has a name: that's how we recognize it. When coding in C, we don't need to remember the memory address (phew!), we just use variable names. The compiler handles the translation between the name and the address. That's one less thing to worry about.

Giving your variables a name

In C, every variable needs a name. For our classic variable that keeps track of lives, we'd love to call it something like β€œNumber of lives”.

But alas, there are a few rules. You can't name a variable just anything:

  • It can only contain lowercase/uppercase letters and numbers (abcABC012...).
  • The name must start with a letter.
  • Spaces are not allowed. Instead, you can use an underscore _ (the underline-looking thing). That's the only non-letter/number character allowed.
  • You can't use accented characters (Γ©, Γ , Γͺ, etc.).

And here's something super important to know: C (like C++) is case-sensitive. That means it treats uppercase and lowercase letters as different.

So, for example, memory, MEMORY, and mEmOrY are three different variables in C, even though to us they look like the same word!

Here are a few examples of valid variable names: lifePoints, life_points, username, characterName, etc.

Every programmer has their own naming style. In this course, I'll show you how I do it:

  • I start all my variable names with a lowercase letter.
  • If the name has several words, I capitalize the first letter of each new word.

I'll ask you to follow the same method for now β€” it'll help keep us on the same page.

Whatever you do, try to give your variables clear names. Sure, you could shorten lifePoints to lp, and yeah, that's shorter, but it's also way less readable when you're reviewing your code later. Don't be afraid to use longer names that actually make sense.

Variable Types

As you'll see, your computer is basically a (very big) calculator. It only knows how to handle numbers.

But here's a fun fact: there are different types of numbers!

For example, we've got positive whole numbers:

  • 47
  • 398
  • 5650

Then we've got decimal numbers (numbers with a decimal point):

  • 75.901
  • 1.7741
  • 9810.8

And of course, we've also got negative integers:

  • -88
  • -916

...And negative decimal numbers!

  • -76.9
  • -100.11

Your poor computer needs a little help here! When you ask it to store a number, you need to tell it what kind of number it is. It's not that it can't figure it out on its own, but... it really helps it stay organized and use memory more efficiently.

When you create a variable, you have to specify its type. Here are the main variable types in C:

Type NameRange of Values
char-128 to 127
int-2,147,483,648 to 2,147,483,647
long-2,147,483,648 to 2,147,483,647
float~Β±3.4 Γ— 10^38
double~Β±1.7 Γ— 10^308

I haven't listed all the types, but those are the main ones. Thankfully there are no complex numbers.

The first three types (char, int, long) are for whole numbers: 1, 2, 3, 4... The last two (float, double) are for decimal numbers: 13.8, 16.911...

float and double can hold huge decimal numbers.

If you don't know what powers of 10 are, just imagine that a double can store the number 1 followed by 308 zeros! That is: 100000000000000000000000000000000000000000000... (nope, I'm not typing 308 zeros for you :D)

You might notice int and long seem the same. That wasn't always true β€” int used to be smaller β€” but modern systems have more memory, so the difference is kinda irrelevant today. C still keeps all those types around for backward compatibility, even if some of them are now overkill.

Personally, I mostly use char, int, and double.

Most of the time, we'll be using integers (good news β€” they're easier to handle ^^).

But wait, there's more! For the integer types (char, int, long...), there are also unsigned versions, which can only hold positive values. You just add the word unsigned in front of the type:

TypeRange of Values
unsigned char0 to 255
unsigned int0 to 4,294,967,295
unsigned long0 to 4,294,967,295

As you can see, the downside of unsigned types is that they can't store negative values. But the upside is they can store values twice as large (e.g. char stops at 127, but unsigned char goes up to 255).

Why do we need three types for integers? Wouldn't one be enough?

Yes, one might've done the trick. But originally, these types were made to help save memory. So if you tell your computer you need a char variable, it'll reserve less memory space than if you'd used int.

That mattered more back in the days when memory was super limited. These days, modern machines have tons of RAM, so it's not a big deal. Don't stress too much about choosing the β€œperfect” type. If you're unsure whether a variable might get a big value, just use int. Seriously. Don't overthink this right now ;)

So in short, we mainly care about whether a number is whole or decimal:

  • For an integer, use int (most common)
  • For a decimal, go with double

Declaring a Variable

Now we're getting to it. Go ahead and create a new console project called "variables".

Let's learn how to declare a variable β€” that is, how to ask the computer for a little slice of memory.

Declaring a variable is super easy once you know the basics :)

Just follow this order:

  • The type of the variable you want to create
  • A space
  • The name you want to give it
  • And don't forget the semicolon!

For example, to create an int variable called lifePoints, you write:

int lifePoints;

And that's it! :D

Here are a few silly examples just for practice:

int schoolGrade;
double moneyReceived;
unsigned int programUsers;

I think you get the idea by now :D

This process is called declaring a variable (yes, learn that term ^^) You need to declare variables at the start of your functions. For now, we only have one function (the main function), so you'll declare it like this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) // Same as int main() { // Start of the function int lifePoints;

return 0; // End of the function }

If you run the code above, you'll be shocked to find... it does absolutely nothing o_O

A Bit of Explanation

Okay okay β€” before you start yelling at me and thinking I've been stringing you along, let me explain myself :p

Things are happening, you just can't see them. When the program reaches the variable declaration, it politely asks the computer if it can use a bit of memory.

If everything's fine, the computer responds, β€œSure, make yourself at home.” Usually, there's no issue.

The only time things could go wrong is if there's no more memory left... but that's rare. You'd need to go pretty wild with int variables to fill up all the memory.

So don't worry β€” your variables should be created just fine.

Here's a neat trick: if you need to declare several variables of the same type, no need to write a line for each one. Just separate the names with commas:

int lifePoints, level, playerAge;

This will create three int variables: lifePoints, level, and playerAge.

So What's Next?

Now that we've created our variable, let's give it a value.

Assigning a Value to a Variable

It couldn't be simpler. To assign a value to the lifePoints variable, just do this:

lifePoints = 5;

That's it. You write the variable name, an equal sign, then the value you want to store.

Now lifePoints holds the value 5.

Our full program looks like this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) { int lifePoints; lifePoints = 5;

return 0; }

Again, nothing appears on screen β€” it all happens in memory. Somewhere deep in your computer's guts, a little memory slot just got the value 5. Isn't that beautiful? :)

I'm getting emotional over here ^^

You can totally change the value later if you want:

int lifePoints;
lifePoints = 5;
lifePoints = 4;
lifePoints = 3;

Here, the variable first holds 5, then 4, then 3.

Since your computer is lightning fast, all that happens in the blink of an eye. You won't even have time to blink before the variable's been through all those values... and poof, your program's done.

Displaying the value of a variable

We already know how to display text on the screen using the printf function. Now, let's take it a step further and learn how to show the value of a variable using the same function.

We actually use printf the same way as before β€” except this time, we insert a special symbol where we want the variable's value to appear.

For example:

printf("You have %d lives left");

This special symbol I'm talking about is a % followed by the letter d. This combo tells printf what kind of data to display. The d stands for an integer.

There are several other options out there, but to keep things simple, let's stick with just these two for now:

SymbolMeaning
%dInteger (e.g., 4)
%fDecimal number (e.g., 7.88)

I'll cover the other symbols later β€” like for strings, special characters, etc. For now, just remember: if you want to print an int, use %d; if it's a double, go with %f.

Almost there! We've told printf where to place an integer β€” but we haven't said which integer yet. So now we need to tell it which variable's value we want to show.

To do that, you simply type the variable name after the quotes, separated by a comma, like this:

printf("You have %d lives left", numberOfLives);

Here, the %d gets replaced by the variable you pass in after the comma β€” in this case, numberOfLives.

Wanna try it out in a little program? :)

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) { int numberOfLives = 5; // At the start, the player has 5 lives printf("You have %d lives\n", numberOfLives); printf("**** B O O M ****\n"); // Boom! They walked on a landmine numberOfLives = 4; // Lost a life! printf("Oh no, you're down to just %d lives now!\n\n", numberOfLives); return 0; }

You could almost call that a video game! (You just need a lot of imagination ^^)

This program displays the following:

You have 5 lives
**** B O O M ****
Oh no, you're down to just 4 lives now!

You should be able to follow what's happening in the program:

  • First, the player has 5 lives β€” we show that with a printf
  • Then they take a hit/get blown up/fall from a cliff (hence the BOOM)
  • Finally, they're left with 4 lives β€” and we show that too with another printf

So yeah, pretty straightforward stuff ^^

Printing Multiple Variables in a Single printf

You can actually show the values of multiple variables in the same printf. Just insert a few %d or %f markers wherever you want, and then list the corresponding variables in the same order, separated by commas.

printf("You have %d lives and you're at level %d", numberOfLives, level);

Make sure to keep your variables in the correct order. The first %d will be replaced by the first variable (numberOfLives), the second %d by the second (level). If you mix up the order, your message won't make much sense anymore.

Let's run a quick test. (I'll skip the lines at the top β€” the # directives. I'll assume you're adding them yourself from now on.)

int main(int argc, char *argv[])
{
  int numberOfLives = 5, level = 1;
  
  printf("You have %d lives and you're at level %d\n", numberOfLives, level);
  
  return 0;
}

Which will display:

You have 5 lives and you're at level 1

Getting User Input

Okay, now variables are about to get really interesting. We're going to learn how to ask the user to type a number into the console. We'll then grab that number and store it inside a variable. Once that's done, we can start doing all sorts of things with it β€” you'll see.

To ask the user to input something in the console, we use another built-in function: scanf.

This one is very similar to printf. You use %d to tell it that the user should enter an integer (I'll come back to decimals in a sec).

Then you specify the variable that should store the number.

Here's how it looks:

int age = 0;
scanf("%d", &age);

You need to wrap the %d in quotes, and you must put an & symbol in front of the variable that will store the value.

Wait β€” why the & before the variable name? o_O

Yeah, so here's the thing β€” you're just going to have to trust me on this one. If I try to explain that now, we'll never get out of this rabbit hole, believe me.

But don't worry: I will explain it later. (It has to do with pointers and memory addresses β€” we touched on that earlier in the chapter.) For now, I'm sparing you the confusion. Really, I'm doing you a favor here.

Heads-up: If you want to let the user enter a decimal number (a double), you don't use %f like you might expect... You use %lf. That's one small difference between scanf and printf. printf is fine with %f, but scanf wants %lf.

double weight = 0;
scanf("%lf", &weight);

Back to our example. When your program hits a scanf, it pauses and waits for the user to enter a number.

Whatever they type gets stored in the variable β€” like "age" in this case.

Here's a simple little program that asks the user for their age and then prints it back to them:

int main(int argc, char *argv[])
{
  int age = 0; // We start by setting age to 0
  
  printf("How old are you? ");
  scanf("%d", &age); // Ask the user for their age with scanf
  printf("Ah! So you're %d years old!\n\n", age);
       
  return 0;
}

How old are you? 20
Ah! So you're 20 years old!

Here's what's going on:

  • The program prints β€œHow old are you?” and then pauses.
  • The cursor blinks, waiting for input. You type your age, hit Enter, and the program picks up where it left off.
  • In this case, it just prints the value stored in age: β€œAh! So you're 20 years old!”

And that's the basic idea :)

Thanks to scanf, we can finally start interacting with the user and maybe even ask them for a few... personal details :-Β°

A few extra notes:

  • If you type a decimal number like 3.9, it'll get truncated β€” only the whole number part is kept. So in that case, the value stored would be 3.
  • If you type in random letters (β€œahfrunhde7261”), the variable won't change. That's the nice thing about initializing your variable to 0 at the start β€” if the input fails, the program will still say β€œ0 years old.”
  • If we hadn't initialized the variable, it could've printed anything! Total chaos!

That's all for the chapter on variables. As I keep repeating, variables are used all the time in programing. All the time. If you understood that variables are just a simple way to store information in memory, you have pretty much everything (99%) figured out already! See you next chapter.

Learn C Programing for Beginners

Enjoyed this C / C++ course?

If you liked this lesson, you can find the book "Learn C Programing for Beginners" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete C / C++ workshop with many exclusive bonus chapters.

More information