Saturday, November 25, 2017

Variable Declaration in C

Now we can print using C program but it is not the only thing we want to do. A lots of things are still remaining.

If we want sum of two numbers from calculator then first we need to put one number and then we need a command (+ sign for addition) which operation we want to do and then we need to put another number. After that if we press equal (= sign) only then calculator will show summation of that two numbers by doing addition operation.


How can calculator remember this two number or calculator stores those number and command? Can you figure out this answer? Let me know if you can.

Let’s back to the topic, variables. What is variable? Simply a variable is a name or identifier by which we can identify them. If we want to use any character, number or others data in our program we need to store them first.


We can compare variable with a container or box. If we have 5 boxes and each one has an unique name then we can easily identify them by their name. Like this, a variable is an unique name of a particular location of memory in our computer. This location in a memory is used to store data.


Before using any variable we need to declare it first. How to declare a variable? Let’s see some example :

If you look into the above example then you already figured out a common pattern in variable declaration. Every variable has two part.First part is its data type and second part is its name.


Structure/Syntax of a variable(in declaration) :

In our above example for first two variables data type is int (ex 2, 3, 10) and for the third variable is double (ex 1.3, 4.87) and all these three variables are unique by their name so that we can identify them.


We can declare same or different types variable as many as we want but their name should be different.


Setting / Assigning Value

If we want to set a number in our variable, how can we do this? Simple! just use a equal sign to set any value. For an example if i want to set 10 in a variable name value;

Declaring variable int Number;
Assigning value Number = 10;

Or we can do this in another way
Declaring & Assigning value int Number = 10;

Both are same. We can use both in our program.



Rules for naming a C variable:

  • A variable can have both uppercase and lowercase letters, digits and underscore.
  • First character of a variable should be an alphabet or underscore.
  • We can’t use any digit in beginning of an variable.
  • We can’t use special character in variables except underscore.
  • An variable can’t be any keyword.

Rules for naming a variable and identifier are same because variables are also a type of identifier.



No comments:

Post a Comment