Difference between revisions of "Variables, expressions, and operators"

From Tux
Jump to: navigation, search
(Created page with "'''Variables''' in C++ are used for storing values which are usually input, manipulated, and output. Variables must be explicitly declared as a specific data type (e.g. a b...")
 
Line 1: Line 1:
'''Variables''' in C++ are used for storing values which are usually input, manipulated, and output.  Variables must be explicitly declared as a specific data type (e.g. a [[basic data type]]) before usage.
+
'''Variables''' in C++ are used for storing values which are usually input, manipulated, and output.  Variables must be explicitly declared as a specific data type (e.g. [[basic data types]]) before usage.
  
 
==Identifiers==
 
==Identifiers==

Revision as of 23:15, 20 January 2018

Variables in C++ are used for storing values which are usually input, manipulated, and output. Variables must be explicitly declared as a specific data type (e.g. basic data types) before usage.

Identifiers

As in regular mathematics, variables have a name that we call an identifier in C++. Identifiers have various rules and conventions.

Identifier rules

Identifiers must adhere to the following rules:

  • May only contain alphabetic characters, digits, and underscores
  • May not contain any special characters or spaces
  • May not start with a digit
  • May not be a reserved word
  • May not be identical to other identifiers in the same scope

Identifier conventions

Although the following are all legal, identifiers should typically:

  • Not start with an underscore (these are frequently used for header files)
  • Not be all capital letters, unless used as a constant
  • Be descriptive about what is to be stored in them to help with code readability

Identifiers may, additionally, adhere to one of many established naming conventions.

Declaration

A variable can be declared as datatype identifier.

Initialization

Variables can be initialized upon declaration or later. Variables should always have some value placed in them (via input from the user and/or a file or via initialization) before they are used in any calculations or output, otherwise erroneous results may occur.

int age = 30; // Initialization upon declaration

double rate;
rate = 0.05;  // Initialization later

Assignment

Variables can be assigned values as such: x = expression;