PDA

View Full Version : C++ Constant Tutorial



Dusk412
07-09-2008, 06:44 PM
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
07-09-2008, 10:29 PM
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
07-28-2008, 09:31 AM
Note that #define NAME VAL works also.

Freddy1990
07-30-2008, 08:24 AM
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
07-30-2008, 08:37 AM
No, its just that they call initialized variables Literals.