User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







cpp:variables

Variables

Variables are the means of storing data in a program. Say you want to make a calculator, you need to use variables. Say you want to make a program that takes in a word and then modifies it, you need to use variables. Variables can be created and “destroyed”(deconstructing comes later on so don't get your hopes up). The value or information that they store can be changed and in some cases, that you make it so, cannot be. Except for the syntax of the language, you are in control!

To create a variable:

//don't worry about things that have a " * " in the comment, we'll get to those
 
#include iostream        //a pre-processor command *
using namespace std ;    //a declaration of the namespace used *
int main()               //the main function *
{
int var1 ;               //the declaration and naming of a variable
 
return 0 ;               //value return statement *
system ("pause") ;       //a system command telling the screen to pause (freeze whatever is on the screen, don't worry not your computer) *

That is your first program! It doesn't do much though.

Let's analyse the declaration and naming of the variable:

int var1 ;

The syntax of naming a variable is the following [varaible type] [varaible name]

The name of the variable can be whatever you want, except a number, but it is good programming practice to make it a descriptive title corresponding to what the variable stores.

This is a list of the most common types of variables:

bool	Stores either value true or false.
char	Typically a single octet(one byte). This is an integer type. (one character)
int	The most natural size of integer for the machine. (a whole number)
float	A single-precision floating point value. (stores a decimal number)
double	A double-precision floating point value. (stores a decimal number)
void	Represents the absence of type.
wchar_t	A wide character type.

Now you have allocated memory for the varaible. That is just reserving space for it. You haven't set the value of it yet. When you do, then the space is filled.

Our variable was an “int” or, in Enlish, an integer. Let's make the variable equal to a number.

int var1 ;
var1 = 5 ;

The variable var1 now equals 5. You could also set the value when you declare it like such:

int var1 = 5 ;

Variables can even be equal to each other!

int var1 = 6 ;
int var2 ;    //another integer variable named "var2"
var2 = var1 ; //the value of var2 is now the same as the value of var1 

Useful Tip When making a variable equal to something, you must use this syntax: [the varaible that you want to change] = [the number or existing varaible] ;

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
cpp/variables.txt · Last modified: 2024/02/16 00:48 (external edit)

Impressum Datenschutz