SRL Archive - C/C++ Help and Tutorials

C++ Constant Tutorial


Dusk412

2008-07-09 14:44:30

C++ Constant Tutorial

Description:
This tutorial will teach you all you need to know about C++ constants.

Table of Contents:
I: Introduction
II. Literals
III. Declared Constants
IV. Defined Constants

I. Introduction:
Constants are like variables, except that their value does not change throughout the script.

II. Literals:
This is when you declare a constant just like a variable except you give it a value. Technically you can change it during the script, and it is often done.
int Num = 5;


III. Declared Constants:
This is when you declare a constant just like above, but with const in front of it. Now it cannot be changed.
const int Num = 5;


IV. Defined Constants:
This is when, at the very beginning of script, right after the library includes, you can define constants that you use often to avoid memory-consuming variables. Just start with define then state the identifier and then the value.
#define PI 3.14159265


Other C++ Tutorials:

C++ Compiler Tutorial:
http://www.villavu.com/forum/showthread.php?t=32498?p=428885#post428885

C++ Variable Tutorial:
http://www.villavu.com/forum/showthread.php?t=32499?p=428888#post428888

C++ Constant Tutorial:
http://www.villavu.com/forum/showthread.php?t=32500?p=428889#post428889

C++ Operator Tutorial:
http://www.villavu.com/forum/showthread.php?t=32501?p=428891#post428891

boberman

2008-07-09 18:29:14

constants are useful for code management. often times you will have places where you use the same number, over and over again. A constant makes it so that you can change all instances of that number quickly and painlessly. while avoiding changing something you don't want to.

A key difference between constants and variables is that constants are often used globally while it is considered very bad practice to use a variable globally.

R0b0t1

2008-07-28 05:31:28

Note that #define NAME VAL works also.

Freddy1990

2008-07-30 04:24:41

Wowmygodzor, it worked, I just know it all now :p
Bit short :)
Aren't your literals just pre-initialized variables? Because seeing you can change their values at runtime they wouldn't count as constants…

R0b0t1

2008-07-30 04:37:03

No, its just that they call initialized variables Literals.