Variable
is a named storage location in the computer's memory where you can store and manipulate data. Each variable has a specific data type, which defines the kind of data it can hold, such as integers, floating-point numbers, characters, and more. Variables provide a way to work with and manage data in a program.
Declaration of Variables:
Variables must be declared before they are used. The declaration includes the data type and the variable's name.
int
age
;
double
salary
;
char
grade
;
int
age
=
25
;
double
salary
=
50000.75
;
char
grade
=
'A'
;
Rules for naming variables:
1. Variable names must begin with a letter (uppercase or lowercase) or an underscore (_).
2. C++ is case-sensitive, so myVariable and MyVariable are treated as different variables.
3. After the first character, variable names can include letters (uppercase or lowercase), digits, and underscores.
4. Variable names cannot contain spaces or most special characters.
5. Avoid using keywords reserved by the C++ language as variable names.
int
myVariable
;
int
User age
;
char
23_myVariable
;
int
_myVariable
;
int
class
;
Variable Scope:
Variable scope in C++ refers to the region or portion of the program where a particular variable is accessible or visible. The scope of a variable determines where in the program the variable can be used and accessed.
There are primarily two types of variable scope in C++:
1.Local scope
2. Global scope
1. Local Variables:
Local variable is a variable that is declared within a specific block, function, or a set of curly braces. Local variables are only accessible and visible within the scope in which they are declared. Once the scope is exited, the local variable goes out of scope and cannot be accessed.
void
myFunction
() {
Copy Code
int
localVar
=
10
;
}
int
main
() {
return
0
;
}
2. Global Variables:
Global variable is a variable that is declared outside of any function, block, or class. Unlike local variables, which have limited scope within a specific block or function, global variables have a scope that extends throughout the entire program. This means that global variables are accessible from any part of the program, including all functions and blocks.
int
globalVar
=
50
;
Copy Code
void
myFunction
() {
}
int
main
() {
return
0
;
}
Comments:
A comment is a portion of the code that is not executed by the compiler. It is added to provide explanatory notes or documentation within the source code. Comments are intended for human readers to understand the code better, and they have no impact on the program's functionality or behavior.
1. Single-line comments:
Denoted by
//
and anything following
//
on a line is treated as a comment.
int
age
= 2204;
2. Multi-line comments:
Enclosed between
/*
and
*/
. It can span multiple lines.
int
x
=
10
;