variables

In this section we will learn what the variables are and how to use them in C

What Are Variables? And What Does a Variable Mean? (Define variable)

Let’s say you are good at math and someone asked you to do a calculation. The person gives you a list of data (numbers in this case) as an input to your calculation but the list is too much to be memorized!

What you can do is to write those numbers on a piece of paper. Now numbers are registered on the paper and you can easily access them whenever you want.

But let’s say other than the first person, there are 2 more people come to you and ask the same request that the first person had.

Again you need to write all the numbers that each person gives you on a piece of paper for later access.

But wait, now because there are people and not just one person, you need to not just write down numbers but also associate each set of numbers to each person.

For example:

Jack-list-of-number: 1,2,3,4,5

Ellen-list-of-number: 20,1,33,2,3

Donald-list-of-number: 0,20,10,111,8

By labeling each set of numbers, we can now easily find each person’s list of numbers and if in the future there was a need to modify any list associated to each person, we can do so without worrying about unknowingly modifying wrong person’s list.

Tagging here in this example helped us to separate each data from the other.

You need to know that these tags just helped us to organize inputs! Without them, the list could still be written down on the paper but it would confuse us and there’s a chance of picking up a wrong list and associate it with a wrong person.

In the world of C programming, these labels and tags are called variable.

You see, pretty much all programs need data. For example, a music player program needs music data; an image viewer needs image data; a calculator needs number data etc.

But programs for the majority of times get more than one data and so we need to put a name on each one of them so then at later times finding and accessing data becomes easy. (Just like we did in the example above)

C Variables Syntax

Data-type variable-name;

Variable Types in C

The data-type is explained in data-type section. but in short it serves two purposes:

  1. Helping compilers to decide the type of value that can be
    assigned to that particular variable:

A character string values like “this is a string of characters”, Integer values like 1, 2, 3, 4, float values like 2.3, 4.2, 1000.323, 1.00 etc. all these values are of different types and categories and compilers do care about types! When we declare the type of a variable, from that moment forward we can only assign that type of value to the target variable.

For example:

int firstNumber;

The variable named firstNumber is of type int (which stands for integer) and so we can only assign integer numbers (without fraction) to this variable.

For example:

firstNumber = 10;
firstNumber = 0;
firstNumber = -44535;
firstNumber = 4223;

Note: the sign = is not equal sign but assign sign. In C programming == is Equal-Sign. You can learn more about them in Operators section.

  1. Helping compilers to decide how much space in memory should be
    set aside for that particular variable!

Each data type takes different amount of space in the memory comparing to the other. For example, a variable of type int takes enough memory space that we can store values range from -2,147,483,648 to 2,147,483,647. But what if we wanted to store a larger number like 4,000,000,000? In that case we need a type that can take more memory space to allow us for storing larger numbers.
So depending on the range of values, we can decide how big the internal memory space for the target variable should be by choosing a data-type.

Note: the memory space for data-types is system-dependent. This means in one system, a data type like int might take 4 bytes and in another one might take 2 bytes. As a result, one system might allow a larger range of values and the other might go for lower range.

Identifiers in C

A Variable-name which is known as identifer is used to access a memory location. This name is like a label or a door if you will to a memory space. Basically, the name of a variable is the pointer to a location in memory where a value can be put in or get from that location.

For example:

int age = 22;
float weight = 532.03;

In this example, the compiler will set aside two locations in memory one that the variable age will point to and one that the variable weight will point to.

So when we assigned the value 22 to the variable age, behind the scene this value is actually putted in the location that the age variable pointing at. Likewise, the value 532.03 is actually putted in the memory location that the variable weight is pointing at.

Variable declaration in C

The process of creating a variable is called declaring a variable.

For example:

int b;
float ff;

Here two variables b and ff are declared. But they don’t have any value assigned to them yet.

Variable initialization in C

The process of putting a value to the variable is called assigning value and if we assign a value right where the variable is declared or basically the first time of assigning a value to a variable, the process is called initialization.

This is the structure:

Data_type variable_name = value;

For example:

int var1 = 20;
long var2 = 1000;
double var3 = 3.4;
char character = 't';

Naming Variables in C: Naming Conventions

There are some rules that we need to follow when we want to set a name for a variable:

  • The name that we use for a variable can contain letters, numbers
    and underscore (_). For example: jack, ellen2020, _black, sunnySeason
    etc.

  • A name for a variable can begin with either underscore or letter.
    For example: _sum, check_point etc.

  • We can’t use white space and special characters like !@#
    %^&*()+ etc. in a variable’s name. For example, these names are
    illegal: ell en, %%jack, Tony&&, pre-process.

  • The C language is case sensitive which means a variable named
    `ellen` is different than a variable named `Ellen` or `ELLEN`.

  • We can’t create two variables with the same name in the same
    function or scope. But we can have two variables with the same
    name each live in different function or one live in one function and the
    other live in the global scope (outside all other functions).

  • We can’t use C-language reserved keywords as the name of a
    variable.

C Reserved Words

Here’s the list of reserved keywords:

auto extern short while
break float signed _Alignas
case for sizeof _Alignof
char goto static _Bool
const if struct _Complex
continue inline switch _Generic
default int typedef _Imaginary
do long union _Noreturn
double register unsignd _Static_assert
else restrict void #_Thread_local
enum return volatile
  • Semicolon `;`: the process of creating a new variable is called
    `declaration statement` and any declaration statement ends with
    semicolon `;` in C.

Note: We only use data types once when we're declaring a variable. From that moment afterward, assigning values to a variable does not need mentioning the type of the variable anymore.

For example:

int firstNumber;
firstNumber = 100;

As you can see the second line did not include the type of the variable.

Example: creating C variable

Let’s take a look at a simple example:

int main() {

int firstNumber;
int secondNumber; scanf("%d %d", &firstNumber , &secondNumber); int sum = firstNumber + secondNumber;

printf("sum: %d",sum);

return 0;
}

In the program above, the whole idea is to get two numbers from a user and add those numbers together and send the result to the output stream.

Now let’s get into details:

There are three variables in this example: firstNumber, secondNumber and sum.

The variables firstNumber and secondNumber are declared and there wasn’t any initialization where the declaration happened. The data type of these three variables are int. This means they can store integer values.

After that we have a call to the scanf() function. For now, don’t worry about how this function works! Just remember that this function takes inputs from users and assign those inputs to variables.

So here we asked this function to take two input values from users and assign those values to the firstNumber and sercondNumber respectively.

After that we have the sum variable.

The sum variable is declared and initialized in one statement. The value that this statement is taking is the sum of values in the firstNumber and secondNumber variables.

Note: in the assignment operators section you’ll learn how to assign a value to a variable but in short one of the simplest and most used one is the assignment = operator where the values on the right side of this operator will be assigned to the variable on the left side.

So here the values of the firstNumber and secondNumber variables will be added together and the result will be assigned to the sum variable.

Locations where we can declare a variable in C:

Variables can be declared inside a function or outside of it.

If a variable is declared inside a function it is called local-variable which is only accessible in that function and not any other functions. Also if a variable is created outside of all functions it is called global-variable which is accessible within any function of that program.

Local variables in C Example:

#include <stdio.h>

int
sum();

int main() {

int firstNumber = 100;
int secondNumber = 200;
sum();
return 0;
}

int sum(){

return firstNumber + secondNumber;
}

Here we have declared two variables within the body of the main function and tried to access them within the body of the sum function. But we will get error when the compiler tries to compile this source code because we used the firstNumber and secondNumber in the sum function but this function cannot see these two variables and their values because they are declared within the body of the main function and so the sum function consider them as undeclared variables!

Basically to the eyes of the sum function, these two variables does not exist at all because they are not declared outside of all functions nor in the body of the sum function itself.

Note: a function can only see and work with variables that exist globally or within the body of that function. Check the function section for more information.

Now if we declare the two variables outside the main function (AKA globally), then these two variables will be visible to the eyes of sum function.

Global variables in C Example:

#include <stdio.h>

int
sum(); int firstNumber;
int secondNumber; int main() {

firstNumber = 200;
secondNumber = 300;

int result = sum();

printf("result: %d",result );
return 0;
}

int sum(){

return firstNumber + secondNumber;
}

If you compile and run the example above, you’ll see that the result is 500.

This is because we have declared the two variables outside of any functions and so any function in the source code can access them and change their values if needed and these changes will be visible to other functions as well.

Multiple variable declarations in C:

In C it is possible to declare multiple variables just in one statement.

This is the structure of creating multiple variables in one statement:

Data-type variable_one, variable_two, variable_n;

In this structure, each variable is separated via colon ,.

For example:

int variable_one, variable_two, variable_n;

In the example above, we’ve created 3 variables of type int.

Note: we could also assign values directly to each variable if we wanted.

For example:

int variable_one = 10, variable_two = 30, variable_n = 50;

C Variable Reading

Reading a variable means getting the current value in that variable.

In order to get the value of a variable anywhere in a program, all we need to do is to simply call that variable.

Note: as long as this call is not on the left side of an assignment operator, the value of the target variable will return. But if we put a variable on the left side of an assignment operator, the variable will act as taker and not a giver! Basically, in that position, we’re able to assign a new value to the variable instead of taking a value from it.

Example: Reading a variable in C

#include <stdio.h>
int main() {
int firstNumber = 200;
int secondNumber = firstNumber;
printf("The value of the secondNumber variable is: %d",secondNumber );
return 0;
}
Output:
The value of the secondNumber variable is: 200

Here the firstNumber variable was first on the left side of the assignment = operator. This means in such a position, the variable is capable of receiving a value and replace its current value (if any) with a new one.

At the second statement we can see the firstNumber is now on the right side of the assignment operator, this means the variable now returns its current value (it will return a copy of whatever is in its memory). So here a copy of this value is assigned to the secondNumber variable.

Constant Variables: What is the Constant Variable?

Sometimes we have a variable and want to assign a value to it once and after that only read the value. Basically, we don’t want to accidentally or intentionally assign a second value to the variable after its initialization.

This is an example of constant variable! Basically in C we can create variables that after their initialization, they won’t accept any other values throughout the lifetime of the program.

In order to create a constant variable, we use the keyword const.

Note: In the constant qualifier section we will get into this topic in a greater detail.

Example: creating constant variables in C

#include <stdio.h>
int main() {
double const pi = 3.14;
printf("The value of the pi variable is: %f",pi );
return 0;
}
Output:
The value of the pi variable is: 3.15

Here pi is constant and so we can’t reassign a value to it after its initial value. If we do so, we will get a compile time error.

Example: C constant identifier

#include <stdio.h>
int main() {
double const pi = 3.14;
pi =2323.342;
printf("The value of the pi variable is: %f",pi );
return 0;
}
Output:
error: assignment of read-only variable 'pi'
pi =2323.342;

As you can see, because we’ve tried to reassign a value to a constant identifier, we got a compile time error.

Difference between Constant and Variable

A variable is capable of reassigning its current value as many times as needed in a program. But a constant identifier as the name suggest, only takes an argument once and there’s no way to reassign it later in a program. If we do so we will get a compile time error.