Friday, July 31, 2015

What are variables in C++ and how do you declare them?

Please review this previous post before you dig into this post.

A variable is a portion of the memory to store a value very similar to your pigeon-hole in your mail office at work.


PigeonHole.png

This picture shows all mailboxes of same size, in C++ and other programming languages you have variables of different sizes and the above analogy has to be modified. The idea that a variable indicates the storage in memory is valid.

In order to declare a variable you need a name and type. The name can be anything other than the names reserved for its (C++ Program) use. You can find them in references (for example: http://cs.smu.ca/~porter/csc/ref/cpp_keywords.html).

The type however, depends on what the variable stands for, such as, is it an integer or a floating point; is it a single character or a bunch of characters; does it represent time in some fashion? etc.

Declaring variable that are integers

The following three lines declare three integers

int a;
int z;
int axc;


The following line declares 3 integers as well. Note that to declare in a single line all of them should be of the same type. This is a short hand for declaring more than one variable.

int result1, result2, result3;

Just declaring a variable is not enough, to work a program, you need to provide a value to the variable, that is called assigning a value.3

Assuming you declared variables as indicated earlier, now the following lines assign values to them:

a=6;
z=19;
axc=1500;


Once you have a bunch of varibales declared and assigned as above you can operate on them in various ways;

result1=a+z; //(this should produce the result 25
result2=axc/(a+z);//(this should produce the result 60)
result3=axc/100;// (this should produce 15)

Here the operators are + (add), and / (divided by)

Now this is all put inside a project called Variables_01 as shown using Visual Studio Express 2015 for Windows Desktop. Of course you can use any other program with C++ compiler.

I assume you reviewed the post mentioned earlier, if not go back and review.

You need to reference in your stdafx.h file as shown:
-----------------
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once
#include "targetver.h"
#include
#include
#include

-----------------------

Variables_01

Build and run this program, the result displayed as shown.

Variables_01_1
 

No comments: