Mark As Completed Discussion

We've learned that we can assign values to a variable, whose type we've declared. We can modify this value as per our requirement; hence, it is called a variable in namesake.

The syntax is [data type] [variable name] = [value]; such as int stockPriceToday = 150;. The value of stockPriceToday will remain 150 until it's changed manually in the code. Similarly, stockPriceToday = 155; changes its value to 155.

Understanding Variables and Constants

C++ also allows us to declare constants using const keyword. A constant is similar to a variable, but its value remains unchanged throughout the execution of a program. It's used when you want to safeguard the value and ensure it's not getting modified by code. An example is const int stockPriceYesterday = 145;. It cannot be modified later in the code.

Every variable and constant in C++ has a certain scope and lifetime which determines its accessibility and when it's deallocated from the memory. In the next screen, we will delve deeper into the scope and lifetime of variables and constants.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment