Unlocking the Power of C++: Variables, Constants, and Literals
Storing Data with Variables
In the world of programming, a variable is a container that holds data. Think of it as a labeled box where you can store a value. Each variable has a unique name, known as an identifier, which helps you access and manipulate the stored data. For instance, consider a variable named age
that stores the integer value 14. The beauty of variables lies in their ability to change values, making them a fundamental building block of programming.
Crafting Meaningful Variable Names
When naming variables, there are certain rules to keep in mind:
- A variable name can only consist of alphabets, numbers, and the underscore
_
. - It cannot start with a number.
- It’s a good practice to begin variable names with a lowercase character.
- Avoid using keywords, such as
int
, as variable names. - While allowed, starting a variable name with an underscore is not recommended.
Remember, the goal is to create meaningful names that make your code easy to understand. For example, first_name
is a better variable name than fn
.
Immutable Values with Constants
In C++, you can create variables whose values cannot be changed using the const
keyword. This ensures that the value remains constant throughout the program. For instance, you can declare a constant named LIGHT_SPEED
using the const
keyword. Attempting to modify its value will result in an error.
The Power of Literals
Literals are fixed values that can be used directly in your code. They cannot be changed, making them a fundamental aspect of programming. Examples of literals include 1
, 2.5
, and 'c'
. These values are hardcoded and cannot be reassigned.
Exploring Different Types of Literals
C++ supports various types of literals, including:
Integer Literals
Integer literals represent numeric values without fractional or exponential parts. There are three types of integer literals:
- Decimal (base 10):
0
,-9
,22
, etc. - Octal (base 8):
021
,077
,033
, etc. (note: octal literals start with a 0) - Hexadecimal (base 16):
0x7f
,0x2a
,0x521
, etc. (note: hexadecimal literals start with a 0x)
Floating-Point Literals
Floating-point literals are numeric values with either a fractional form or an exponent form. Examples include:
-2.0
0.0000234
-0.22E-5
(note: E-5 represents 10^(-5))
Character Literals
Character literals are created by enclosing a single character inside single quotation marks. Examples include:
'a'
'm'
'F'
'2'
'}'
String Literals
String literals are sequences of characters enclosed in double-quote marks. We’ll dive deeper into strings in a future tutorial.