0% found this document useful (0 votes)
23 views14 pages

Variables 1. Variable

The document provides an overview of variables in C++, including their characteristics, types, initialization methods, and rules for naming. It also covers primitive data types, constants, and the importance of using constants for readability, maintainability, and error prevention. Additionally, it includes examples to illustrate the concepts discussed.

Uploaded by

saimnaeem9020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views14 pages

Variables 1. Variable

The document provides an overview of variables in C++, including their characteristics, types, initialization methods, and rules for naming. It also covers primitive data types, constants, and the importance of using constants for readability, maintainability, and error prevention. Additionally, it includes examples to illustrate the concepts discussed.

Uploaded by

saimnaeem9020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Variables

1. Variable:
In programming, variables are used to store and manipulate data during
program execution. They are likey name containers that hold or store
information which can be modified during program execution.

Key Characteristics of Variables:


1. Name: A unique identifier (e.g., age, score) used to reference the
variable.
2. Data type: Specifies the type of data the variable can hold (e.g., integer,
float, string).
3. Value or intialization : The data or information stored in the variable.

Unintialized variable
1 Data_type variable_name; //but this make some errors during program execution
.

3 ways to intialize variable in C++


1. Data_type variable_name = value; //C-like initialization
2. Data_type variable_name {value}; //C++11 , initialization syntax
3. Data_type variable_name (value) ; //constructor initalization

Example in C++:
1. #include <iostream>
2. using namespace std;
int main() {
3.
4. int age = 20; // 'age' is a variable of type int holding the value 20
5. cout << "Age: " << age;
6.
7. return 0; }
8.
9.

Types of Variables in C++:


1. Local Variables
2. Global Variables
3. Static Variables
4. Constant Variables
1. Local Variables:
 Definition: Declared and used inside a function or block. They are
only accessible within that function or block.
 Example:
1. #include <iostream>
2. using namespace std;
3.
4. void display() {
5. int localVar = 10; // Local variable
6. cout << "Local Variable: " << localVar << endl;
7. }
8.
9. int main() {
10. display();
11. // cout << localVar; // Error: localVar is not accessible here
12 return 0;
13. }

2. Global Variables:
 Definition: Declared outside all functions and accessible throughout the
program.
 Example:
1. #include <iostream>
2. using namespace std;
3.
4. int globalVar = 50; // Global variable
5.
6. void display() {
7. cout << "Global Variable in display(): " << globalVar << endl;
8. }
9.
10. int main() {
11. cout << "Global Variable in main(): " << globalVar << endl;
12. display();
13. return 0;
14. }
15.
3. Static Variables:
 Definition: Retain their value between function calls. Declared using the
static keyword.
 Example:
1. #include <iostream>
2. using namespace std;
3.
4. void staticExample() {
5. static int counter = 0; // Static variable
6. counter++;
7. cout << "Static Variable Value: " << counter << endl;
8. }
9.
10. int main() {
11. staticExample(); // Output: 1
12. staticExample(); // Output: 2
13. staticExample(); // Output: 3
14. return 0;
15. }

4. Constant Variables:
 Definition: Declared with the const keyword and cannot be modified
after initialization.
 Example:
1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. const int constVar = 100; // Constant variable
6. cout << "Constant Variable: " << constVar << endl;
7.
8. // constVar = 200; // Error: Cannot modify a constant variable
9. return 0;
10 }
.

Rules for Naming Variables:


1. Must begin with a letter or an underscore (_).
2. Cannot contain spaces or special characters (except _).
3. Cannot use reserved keywords (like int, return).
Key Differences:
Type Scope Lifetime Modifiable
Local Variable Inside function/block Until function exits Yes

Global Variable Entire program Entire program Yes

Static Variable Inside function/block Entire program Yes

Constant Variable Varies (local/global) Varies No

sizeof Variables:
The size of operator in C++ determine the size of a type or variable in bytes.
 The sizeof get information from c++ limited includes file or header files
like <climits> and <cfloat> .
 Cfloat is for floating point numbers.
 Climits is used for Integral part number.
Example:
 sizeof (int);
 sizeof (double)
 sizeof (some_variable)
 sizeof some_variable (without pranthcies this feature is only for variables)
Primitive or Fundamental Data Type

Primitive or Fundamental Data Type:

Primitive or Fundamental Data Types are the basic data types provided
by a programming language. These are used to define variables that
store simple data values like numbers, characters, and booleans.
In C++, the primitive data types are categorized into the following
groups:

1. Integer Types
 Definition: Used to store whole numbers.
 Types:
There are different types of integer
 signed int: used for both positive or negative integers.
 unsigned int: used for non-negative or postive integers only.
 int: Default integer type.
 short int (or short): Smaller range.
 long int (or long): Larger range.
 long long int (or long long): Even larger range.

Example:

1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. int num = 10; // Regular integer
6. short int smallNum = 5; // Small integer
7. long int largeNum = 100000; // Large integer
8.
9. cout << "num: " << num << ", smallNum: " << smallNum << ", largeNum:
10. " << largeNum << endl;
11.
12. return 0;
13. }

2. Floating-Point Types
 Definition: Used to store decimal or real numbers.
 Types:
o float: Single-precision floating-point.
o double: Double-precision floating-point (more precision than
float).
o long double: Higher precision.

Example:

1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. float pi = 3.14f; // Float
6. double gravity = 9.81; // Double
7. long double precise = 2.718281828; // Long double
8. cout << "pi: " << pi << ", gravity: " << gravity << ", precise: " << precise
9. << endl;
10. return 0;
11. }
12.

3. Character Type
 Definition: Used to store a single character or symbol.
 Type:
o char: Stores a single character (1 byte or 8bits).
o char16_t: used to store unicode character like U+0041 represents
the letter 'A' , U+1F600 represents the grinning face emoji 😀.
(1 byte or 8bits).
o char32_t: Also used to store unicode characters. (4byte or 32 bits)
o wchar_t: Stores a wide character, often used for international
character sets.(2 or 4 bytes)
o String data type: While not strictly character types, string data
types are used to store sequences of characters.
Like std::string str= “Hello, World!” << endl; etc
Example:

1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. char grade = 'A'; // Character type
6. cout << "Grade: " << grade << endl;
7. return 0;
8. }

1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. char ch = 'A';
6. wchar_t wch = 'A'; //to find ASCAII value
7. string str = "Hello, world!";
8.
9. cout << "Character: " << ch << endl;
10. cout << "Wide Character: " << wch << endl;
11. cout << "String: " << str << endl;
12.
13. return 0;
14. }

4. Boolean Type
 Definition: Used to store logical values: true (1) or false (0).
 Type:
o bool: Stores true or false.
Example:
1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. bool isPass = true;
6. cout << "Did you pass? " << isPass << endl; // Output: 1 (true)
7. return 0; }

5. Void Type
 Definition: Represents no value or data type. Commonly used for
functions that do not return a value.
 Type:
o void
Example:
1. #include <iostream>
2. using namespace std;
3.
4. void sayHello() {
5. cout << "Hello, World!" << endl;
6. }
7.
8. int main() {
9. sayHello();
10.
11. return 0; }

Summary Table:
Data Type Size (in bytes) Example Value
int 4 (standard) 100
float 4 3.14
double 8 9.81
char 1 'A'
bool 1 true / false
void 0 Used in functions

Constant
Constant
Constants in C++
In C++, constants are fixed values that cannot be changed during the
program's execution. They are used to represent values that remain
constant throughout the program's lifetime.
Types of constants:
 Literal constants
 Declared constants (const keyword )
 Constant Expressions (constexp keyword )
 Enumerated Constants (enum keyword)
 Defined Constants (#define)
1. Literal constants:
 These are values directly written in the code.
 They are assigned a data type based on their form.
Example:
1. // Integer literals
2. int num1 = 10;
3. int num2 = -25;
4.
5. // Floating-point literals
6. double pi = 3.14159;
7. float radius = 3.5f;
8.
9. // Character literals
10. char initial = 'A';
11.
12. // String literals
13. std::string greeting = "Hello, world!";

Examples:
Integer and float literal with Suffixes: Character literal Constants (escape codes)
12 -an integer \n -new line \\ -backslash
12U -an unsigned integer \r -return
12L -an long integer \t -tab
12LL -an long long integer \b -backspace
12.1F -a float \’ -single qoute
12.1L -a long double \” -double qoute

3. Declared Constants (const Keyword)


 These are variables declared with the const keyword, making their values
unchangeable after initialization.
They provide type safety and readability.

Example:
1. const int MAX_VALUE = 100;
2. const double PI = 3.14159;
3.
4. // Trying to modify a const variable will result in a compilation error
5. // MAX_VALUE = 200; // Error
6.

4. Constant Expressions (constexpr Keyword):


 These are expressions that can be evaluated at compile time.
 They are often used to initialize variables with constant values.
Example:
1. constexpr int square(int x) {
2. return x * x;
3. }
4.
5. int main() {
6. constexpr int area = square(5); // Evaluated at compile time
7. // ...
8. }
9. //Other example
10. constexpr int x = 10 + 20; // Evaluated during compile time

5. Enumerated Constants (enum Keyword)


 These define a set of named integer constants.
 They are useful for creating a set of related values.
Example:
1. enum Color {
2. RED,
3. GREEN,
4. BLUE
5. };
6.
7. Color favoriteColor = BLUE;

6. Defined Constants (#define Preprocessor Directive)


 These are defined using the #define preprocessor directive.
 They are replaced with their values before compilation.
Example:
1. #define PI 3.14159
2.
3. int main() {
4. double area = PI * radius * radius;
5. // ...
6. }

Key Points:
 Literal constants are the most basic form of constants.
 Declared constants provide type safety and make code more readable.
 Constant expressions are evaluated (When something is evaluated
during compile time, it means that the compiler determines its value or
behavior while it is compiling the program, rather than waiting until the
program is running ) at compile time, improving efficiency.
 Enumerated constants define a set of related values.
 Defined constants are replaced with their values before compilation, but
they lack type safety.

Why Use Constants?


1. Readability:
o Makes code more readable and understandable by giving
meaningful names to fixed values.
2. Maintainability:
o Centralizes the definition of constants, making it easier to modify
them in one place if needed.
3. Error Prevention:
o Prevents accidental modification of values, reducing the risk of
bugs.
4. Efficiency:
o In some cases, the compiler can optimize code that uses
constants, leading to faster execution.

1. #include <iostream>
2. using namespace std;
3.
4. int main() {
5. cout << "Hello, Welcome to saim carpet cleaning service" << endl;
6. cout << "\nHow many rooms would you like cleaned? : ";
7. int number_of_rooms = 0;
8. cin >> number_of_rooms;
9.
10 cout << "\nEstimate for carpet cleaning service " << endl;
. cout << "--------------------------------------------" << endl;
11
. const double price_per_room(30.0), sales_tax(0.06);
12 const int estimate_expiry(30);
.
13 double cost(price_per_room * number_of_rooms), tax(cost * sales_tax),
. total_cost(cost + tax);
14
. cout << "Number of rooms: " << number_of_rooms << endl;
15 cout << "Price per room: " << price_per_room << endl;
. cout << "Cost: $" << cost << endl;
16 cout << "Tax: $" << tax << endl;
. cout << "================================================" << endl;
17 cout << "Total estimate: $" << total_cost << endl;
. cout << "This estimate is valid for " << estimate_expiry << " days" << endl;
18 return 0;
. }
19
.
20
.
21
.
22
.
23
.
24
.
25
.
26
.
27
.
28
.
29
.

You might also like