C++ Variables and Literals and Constants

What Are Variables?

In programming, a variable is like a container that holds data. It allows you to store and manipulate values within your program. Variables have names, data types, and values. Here’s how you declare a variable in C++:

data_type variable_name;
  • data_type: This specifies the type of data the variable can hold, such as int for integers, double for floating-point numbers, and char for characters.
  • variable_name: This is the chosen name for your variable, like age, temperature, or name.

For example:

int age;
double temperature;
char first_initial;

Assigning Values to Variables

After declaring a variable, you can assign a value to it using the assignment operator =

variable_name = value;

For instance:

age = 25;
temperature = 98.6;
first_initial = 'A';

You can also declare and initialize a variable in a single line:

data_type variable_name = value;

Here’s how you can do it:

int age = 25;
double temperature = 98.6;
char first_initial = 'A';

What Are Literals?

Literals in C++ are constant values that are used directly in your code. They are fixed values and do not change during the execution of your program. There are several types of literals in C++:

  • Integer Literals: These are whole numbers without decimal points. For example, 5, -10, or 1000.
  • Floating-Point Literals: These are numbers with decimal points. For instance, 3.14, -0.5, or 1.0.
  • Character Literals: These represent individual characters enclosed in single quotes. Examples include 'A', '5', or '%'.
  • String Literals: These represent sequences of characters enclosed in double quotes. For example, "Hello, World!".
  • Boolean Literals: These can be either true or false, representing the two possible values of the boolean data type.

C++ Constants

Constants are variables whose values do not change throughout the program’s execution. You can declare a constant using the const keyword. For example:

const int max_score = 100;

In this program, we’ve declared variables to store age, temperature, and a first initial. We then use cout to display these values on the screen.

Conclusion

You’ve learned about variables and literals, which are fundamental concepts in programming. Variables allow you to store and manipulate data, while literals represent fixed values in your code. You’ve also seen how to declare, assign values to variables, and use them in a simple program.