C++….Constants

This week I’m going to show you how to do constants. This is a very simple subject to learn and its basically the same as variables but as the name suggests they stay constant. The difference from a variable is that constants save on memory usage where as variables can use up a lot. So lets jump right into things. You all should know if you’ve been keeping up with my lessons how to declare a variable. But what happens when you use something a lot more often and you want to use it in different functions and such. By the way the next lesson is on functions you don’t need to know it right now. So to declare a constant its as simple as this : #define thisnum 1337

That seems simple right? This type of constant is a define constant. It is written with the # symbol because it is read by the preprocessor just like the #include code. Lets use this in a simple program:

#include<iostream>
using namespace std;


#define acid "This is a string from my define constant!"

int main{
cout << acid;
system(pause);
return 0;
}

In this example the word acid is declared in define as “This is a string from my define constant!”. So no matter where you use it in the program acid will always print the string and you won’t have to declare it in different sections. Remember that #define is not a variable but a preprocessor directive. And since it is constant it cannot be changed like a variable. Now with that in mind you can declare constants like variables with declared constants. To use a declared constant you use it in the same way as you would a variable. const int math = 4+4; so lets do an example program:


#include<iostream>
using namespace std;

int main{
const int a = 5;
const int b = 6;
int c;

c = a + b;
cout << a;
cout << b;
cout<<

system(pause);
return 0;
}

So there you go it shouldn’t be too hard to follow now you can use define and declared constants in your programs. Next lesson will be using some loops. As usual any comments or anything can be left in the comments section for this post.