Sunday, 3 January 2016

Variables in C

If you are coming from programming background, you may find this section similar to other programming languages but if not, you can find this section a bit tricky. I will try my best to go into the most detailed discussion.

This is one of the basic thing any programming language will have. The syntax may differ but surely there will be the concept of variables and data types. So, this is very important for any programmer. Try to understand every bit of it, try as many examples as you can. If you are stuck or cannot digest a particular portion of it, comments are welcome.

To start our discussion, we need to understand what a variable is and why do we require them at all.

Think of a person who can't remember anything or have a very short term memory.

What happens to that person ?

Scenario 1: The person rides a bus and gets a ticket for his travel. After sometime, he completely forgets that he had paid for his trip and again purchases another ticket and after a minute or two, he again forgets it and purchases another one or may be the worst case, he forgets where he has to go.

Scenario 2: The person takes his dinner and forgets after a minute or two and again takes his dinner and forgets again and again he takes his dinner until his body stops him to do so or he is killed by over eating.

These scenarios may look funny to the world but it is really not funny for the person who bears all these.

Similar situation can happen to your program if your program does not have a memory.

Let's take a simple program that does not have a memory.
#include <stdio.h>

/*
 * This program calculates the sum each time it requires.
 * Author: Palash Kanti Kundu
 * Since: March 26, 2016
 */
int main(){
        printf("%d\n", (5+6));
        printf("%d\n", (6+7));
        printf("%d\n", (5+6));
        printf("The perimeter of circle with %d radius is %f\n", 8, ((float) 2*22*8/7));
        printf("The perimeter of circle with %d radius is %f\n", 9, ((float) 2*9*22/7));
        return 0;
}
processMultipleTimes.c

In this program, we see that, we do have nothing to store the result of a particular calculation. So, we have to perform the same calculations over and over again. This becomes overhead to the processing unit and also takes more time to execute. Also, the length of the code increases. This is just a program with only 5 calculations. You can imagine the length of the code if it had to perform more than 20 calculations.

Horrible, right ?
At some point, the code will be so clumsy that it would be extremely hard to read or understand what the program wants to do.

So, we have to think of a way that provides more flexibility in terms of code, usability and performance.

Let's rewrite the program where the program deploys some memory to store some of the calculation results.
#include <stdio.h>

/*
 * This program calculates the result and stores in memory.
 * Author: Palash Kanti Kundu
 * Since: March 26, 2016
 */
int main(){
        int i = 5, j = 6, k = 7, radius1 = 8, radius2 = 9;
        float pi = (float) 22/7;
        printf("%d\n", (i+j));
        printf("%d\n", (j+k));
        printf("%d\n", (i+k));
        printf("The perimeter of circle with %d radius is %f\n", radius1, ((float) 2*pi*radius1));
        printf("The perimeter of circle with %d radius is %f\n", radius2, ((float) 2*pi*radius2));

        return 0;
}
processWithMemory.c

Now, you can see the difference, we've deployed some memory to store some of the calculation results and used them as and when required. This time, not only program performs less processing, the code also became more readable.

The second point is obvious, human beings are good at remembering names and not numbers.

Still, our program is not so good, let's make some more changes to make it more elegant that too using memory and user input.
/*
 * This program calculates the sum each time it requires.
 * Author: Palash Kanti Kundu
 * Since: March 26, 2016
 */
int main(){
 int i, j, radius;
  float pi = (float) 22/7;
 printf("Please enter two numbers to add\n");
 scanf("%d %d", &i, &j);
 printf("%d + %d = %d\n", i, j, (i+j));
 printf("Enter the radius:\n");
 scanf("%d", &radius);
 printf("The perimeter of circle with radius %d is %f\n", radius, (2*pi*radius));
 return 0;
}
processUserInput.c

Now this program is more readable, uses less memory and also works with user input. So, you can see that using simple memory blocks in your program always provides more flexibility, more readability and more robustness.

So, this is the point of using memory in our code.

Now, the question is how do we do that ?
We do that using variables.

You already have understood the concept of variable (if not, read again from the begining), now let's find a simple definition.

Variable: Variable is a reserved memory location to store data with a name and also provides a set of operations to be performed on the data. Programmers use the name of the variable to work on.

A variable declaration have the following syntax
data_type variable_name = [value];

If you don't know what do we mean by Data, check this article on Data.

So variable is memory location associated with a name and the particular set of operations that we can perform on that data.

By set of Operations we mean the operations are permitted for a particular variable.

For example, we can perform calculations like 2+2 and we know that the result is 4. Similarly, we can perform 2.3+9.2 and we know that the result is 11.5. We can perform these calculations because addition is legal on two numbers. Also 2 - 1 = 1 and this is a valid calculation. But we cannot do the calculations like, P + A + L or K - U - N. Because, simply these calculations do not have a meaning. We don't know what this calculations are supposed to do. In a nutshell, we don't define these calculations.

Similarly in C we can perform a set of operations on particular variable and cannot perform the same operation on some other variable. The set of supported operations are provided by the Data Type of the variable. The data type also restricts the programmer to assign a restricted set of value for a variable.

For example, we cannot assign a real number to a variable of type integer (whole number).

Another important thing to remember that we cannot use a variable before we declare them.
For example, the following program is invalid.

#include <stdio.h>

/* Program to demonstrate illegal use of variables.
 * Author: Palash Kanti Kundu
 * Since March 26, 2016
 */

int main(){
        printf("Value of C is %d", c);
        int c;
        return 0;
}

inValidVariable.c

This program is invalid because, we are trying to use the variable c before declaring it.
Although we have declared the variable on the very next line, it won't allow the compilation. Because, the compiler does not know what c is used for. May be after the declaration, the programmer may use it in a different way. So, the compiler does not take a chance and throws the error to the programmer. If you remember, computer is good at following instructions like a slave and it will never take a chance or apply its own logic to overcome a situation. Rather, it will scream to the programmer and will ask to correct it.

So, Variable is a name associated with a memory location and a set of supported operations. We declare a variable with its data type and name and use the name throughout the whole program as and when needed.

Now, what a variable name should look like ?

According to the rules of C,
  • Variable names are case sensitive
  •  A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_".
  • Subsequent characters may be letters, digits, dollar signs, or underscore characters.
  • Variable name must not be a reserved word.
  • Name can not contain white spaces.
  • Digit at start is not allowed
This rules alsmost allow every name to qualified as a good variable name. But at times, you may get confused with a variable name like 'abc' or '_un$789'. So, here are some tips while naming your variable,
  • Don't use '$' or '_' as the first character of variable name. It is allowed but not suggested.
  • Please use proper variable names, which can suggest the way this variable is used.
  • If your variable name is span across more than one word, you can capitalize each first letter of each word.
  • While naming constants, use all capitals while separating each word by '_'
Now, let me show you an example with a valid name and meaningful name,
#include <stdio.h>

/* Program to show different names of variables.
 * Author: Palash Kanti Kundu
 * Since March 26, 2016
 */

int main(){
        int $m = 10;
        float PI = (float) 22/7;
        int maximumValue = 10;
}
variableNames.c

In this program, both the names are valid according to the rules of C but anyone can hardly understand what the variable $m does but while looking out the variable PI, anyone can easily understand that this variable is used to store the value of pi and it is used as a constant. or anyone can easily guess that for this program the maximum allowed value is 10 with the help of the variable name maximumValue.

Source Code Distribution

Although it is not a recommended practice, you can download the Source Code of this article. I have my repository hosted in github and published the source code which you can find in https://github.com/Palash90/c/tree/master/src/blog/Variables_in_C

No comments:

Post a Comment