Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Variables | Data
C Basics

book
Variables

Imagine you're working with data from laser distance sensors attached to a remote-controlled car.

Before you can display this distance data on a screen or remove it from memory, you'll need a place to store it. That's where variables come in. Think of a variable as a storage bin within your computer's memory, which you "rent" to hold specific data. Essentially, every program you write will utilize variables, each of a particular type.

Declaring a variable in C involves two steps:

  • Defining the kind of data you'll be storing;

  • Naming this variable.

Here's what that looks like:

c
// int - data type
// qwerty - variable name
int qwerty;

Specifying the data type ensures the computer allocates the right amount of memory for your data. Now that we're familiar with three basic data types, we can declare variables for each:

c
int iVariable; // variable of int type
float fVariable; // variable of float type
char cVariable; // variable of char type

So, once we have a variable, how do we use it? Start by initializing it.

Initialization

To initialize a variable is to assign specific data to that chunk of memory. Given that iVariable is an integer type, you'd assign it an integer value. Similarly, you'd assign a decimal value to fVariable and a character to cVariable.

c
int iVariable = 832; // variable of int type
float fVariable = 54.75; // variable of float type
char cVariable = '#'; // variable of char type

Note

When initializing a char type variable, make sure to use single quotes.

With the data stored in these variables, what can we do next?

One option is to display them on a screen.

c

Main

copy
#include <stdio.h>

int main()
{
int iVariable = 832; // variable of int type
float fVariable = 54.984; // variable of float type
char cVariable = '#'; // variable of char type

printf("iVariable = %d\n", iVariable);
printf("fvariable = %f\n", fVariable);
printf("cVariable = %c\n", cVariable);
}
123456789101112
#include <stdio.h> int main() { int iVariable = 832; // variable of int type float fVariable = 54.984; // variable of float type char cVariable = '#'; // variable of char type printf("iVariable = %d\n", iVariable); printf("fvariable = %f\n", fVariable); printf("cVariable = %c\n", cVariable); }

Curious about the odd characters in the printf() function? We'll dive into that in the next lesson.

question mark

Now, can you select the correct way to initialize a character-type variable?

Select the correct answer

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 2

Vraag AI

expand
ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt