C++ Fundamentals

TechnicsPublications C Fundamentals git.ir
Spread the love

C++ Fundamentals

TechnicsPublications C Fundamentals git.ir

 

C++ Keywords

Keywords in C++ are reserved words that have special meanings and cannot be used for variable names, function names, or any other identifiers. These keywords are part of the C++ language syntax and are used to perform various operations.

Here is a list of some commonly used C++ keywords:

Data Types

  • int: Integer data type.
  • float: Floating-point data type.
  • double: Double-precision floating-point data type.
  • char: Character data type.
  • bool: Boolean data type, representing true or false.

Control Flow

  • if: Starts a conditional statement.
  • else: Specifies the block of code to execute if the condition in the if statement is false.
  • switch: Starts a switch statement to execute one out of many code blocks based on a condition.
  • case: Defines a case within a switch statement.
  • default: Specifies the default code block to execute in a switch statement if none of the cases match.
  • for: Starts a for loop.
  • while: Starts a while loop.
  • do: Starts a do-while loop.

Storage Classes

  • auto: Deduces the type of the variable automatically.
  • register: Suggests that the variable be stored in a register instead of RAM.
  • static: Maintains the variable’s value between function calls.
  • extern: Declares a variable that is defined in another file.

Access Modifiers

  • public: Specifies that class members are accessible from outside the class.
  • private: Specifies that class members are accessible only within the class.
  • protected: Specifies that class members are accessible within the class and its derived classes.

Memory Management

  • new: Allocates memory on the heap.
  • delete: Deallocates memory previously allocated with new.

Exception Handling

  • try: Starts a block of code that will be tested for exceptions.
  • catch: Specifies the block of code to execute if an exception is thrown.
  • throw: Throws an exception.

Miscellaneous

  • return: Ends the execution of a function and returns a value.
  • namespace: Defines a scope to avoid name conflicts.
  • using: Imports a namespace into the current scope.
  • sizeof: Returns the size of a data type or object in bytes.
  • typedef: Creates an alias for a data type.
  • const: Specifies that a variableā€™s value cannot be modified.
  • volatile: Indicates that a variableā€™s value may be changed by external factors.
  • enum: Defines an enumeration, a distinct type consisting of a set of named values.
  • struct: Defines a structure, a user-defined data type.
  • class: Defines a class.
  • union: Defines a union, a data structure where all members share the same memory location.

Example

#include <iostream>
// Define a function that returns the maximum of two numbers
int max(int a, int b){
return (a > b) ? a : b; // Conditional operator

}
int main(){
int x = 5;
int y = 10;
// Use if-else control flow
if (x > y) {
std::cout << "x is greater than y" << std::endl;
} else {
std::cout << "x is not greater than y" << std::endl;
}
// Use a for loop
for (int i = 0; i < 5; i++) {
std::cout << "i = " << i << std::endl;
}
// Use switch-case control flow
switch (x) {
case 5:
std::cout << "x is 5" << std::endl;
break;
default:
std::cout << "x is not 5" << std::endl;
break;
}
// Calculate the maximum using a function
std::cout << "The maximum of x and y is " << max(x, y) << std::endl;
return 0;
}

C++ Identifiers

Identifiers in C++ are names given to various program elements such as variables, functions, arrays, classes, and objects. Identifiers are essential for writing readable and maintainable code. Here are the key points about identifiers:

Rules for Identifiers

  1. Alphabet and Digits: Identifiers must begin with a letter (uppercase or lowercase) or an underscore (_). Subsequent characters can be letters, digits (0-9), or underscores.
    int age; // Valid
    int _height;// Valid
    int 2ndPlace; // Invalid, starts with a digit
  2. No Special Characters: Identifiers cannot contain special characters like @, #, $, etc.
    int value$; // Invalid, contains special character
  3. No Keywords: Identifiers cannot be the same as C++ keywords (e.g., int, return, class).
    int return; // Invalid, 'return' is a keyword
  4. Case Sensitivity: C++ is case-sensitive, meaning age and Age are considered different identifiers.
    int Age;
    int age; // 'Age' and 'age' are different
  5. Length: While there’s no strict limit to the length of an identifier, it’s advisable to keep them reasonably short yet descriptive to enhance readability.

Naming Conventions

To make code more readable and maintainable, follow these naming conventions:

  1. Camel Case: Commonly used for variable and function names.
    int myVariableName;
    void calculateSum();
  2. Pascal Case: Often used for class names.
    class StudentRecord;
  3. Underscores: Used for constants and sometimes for private member variables.
    const int MAX_COUNT = 100;
    int _privateVariable;

Examples of Identifiers

Here are some examples demonstrating valid and invalid identifiers:

// Valid Identifiers
int studentAge;
float totalAmount;
char grade;
bool isValid;
double PI = 3.14159;
// Invalid Identifiers
int 1stPlace;// Starts with a digit
float total-amount; // Contains a special character '-'
char class; // Uses a keyword
bool is Valid; // Contains a space

Example Usage in a Program

#include <iostream>
class Student {
private:
int age;
std::string name;
public:
void setAge(int studentAge){
age = studentAge;
}
void setName(std::string studentName){
name = studentName;
}
void displayInfo(){
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
int main(){
Student student1;
student1.setAge(20);
student1.setName("Alice");
student1.displayInfo(); // Output: Name: Alice, Age: 20
return 0;
}

In this example:

  • Student, setAge, setName, and displayInfo are identifiers for the class and its methods.
  • age and name are private member identifiers.
  • student1 is an identifier for an object of the Student class.
  • studentAge and studentName are identifiers for parameters passed to methods.

C++ Variables, Literals and Constants

Variables

Variables in C++ are used to store data that can be modified during program execution. Each variable must be declared with a specific data type that determines what kind of data it can hold.

Variable Declaration

A variable declaration specifies the data type and the variable name. For example:

int age;
double salary;
char grade;

Variable Initialization

Variables can be initialized at the time of declaration:

int age = 30;
double salary = 50000.50;
char grade = 'A';

Literals

Literals represent fixed values that are directly used in the code. These values do not change and are often referred to as constants in a broader sense (though not in the strict C++ terminology where constants have a specific definition).

Types of Literals

  1. Integer Literals: These are whole numbers without a fractional part.
    10, -100, 0
  2. Floating-point Literals: These represent numbers with a fractional part.
    3.14, -0.001, 2.0
  3. Character Literals: These are single characters enclosed in single quotes.
    'a', 'Z', '1'
  4. String Literals: These are sequences of characters enclosed in double quotes.
    "Hello, World!", "C++ Programming"
  5. Boolean Literals: These represent truth values.
    true, false

Constants

Constants are similar to variables but, once defined, their values cannot be changed. They are often used to define values that are known at compile time and should not be altered.

Defining Constants

  1. Using const Keyword:
    const int MAX_AGE = 100;
    const double PI = 3.14159;
  2. Using #define Preprocessor Directive:
    #define MAX_AGE 100
    #define PI 3.14159

    Note that #define is a preprocessor directive and does not follow the scope rules like const.

Enumerations

Enumerations are a way to define a set of named integer constants.

enum Color { RED, GREEN, BLUE };
Color myColor = GREEN;

Example Code

Hereā€™s a simple C++ program that demonstrates variables, literals, and constants:

#include <iostream>
using namespace std;
const double PI = 3.14159; // Constant
int main(){
int radius = 10; // Variable
double area; // Variable
area = PI * radius * radius; // Using a constant and a variable
cout << "The area of the circle is: " << area << endl; // Using a literal (string) and a variable
return 0;
}

Summary

  • Variables: Named storage that can change values during program execution.
  • Literals: Fixed values used directly in the code.
  • Constants: Named values that do not change after being defined.

C++ Data Types

C++ is a statically-typed language, meaning that variable types must be specified at compile time. This allows for efficient use of memory and can help catch errors early in the development process. Here is a comprehensive overview of the primary data types in C++:

Fundamental Data Types

  1. Integral Types
    • int: Represents integer numbers. It usually occupies 4 bytes.
      int a = 5;
    • short: A shorter version of int, typically 2 bytes.
      short b = 10;
    • long: A longer version of int, usually 4 or 8 bytes depending on the system.
      long c = 100000;
    • long long: An even longer version of int, typically 8 bytes.
      long long d = 1000000000;
    • unsigned: Can be combined with int, short, long, and long long to represent non-negative integers.
      unsigned int e = 50;
  2. Floating-Point Types
    • float: Single precision floating-point. Usually occupies 4 bytes.
      float f = 5.75f;
    • double: Double precision floating-point. Typically 8 bytes.
      double g = 19.99;
    • long double: Extended precision floating-point, often more than 8 bytes.
      long double h = 20.9876543210L;
  3. Character Types
    • char: Represents a single character. Typically 1 byte.
      char i = 'A';
    • wchar_t: Wide character type for larger character sets like Unicode. Size varies by compiler.
      wchar_t j = L'B';
    • char16_t: For UTF-16 characters. Introduced in C++11.
      char16_t k = u'C';
    • char32_t: For UTF-32 characters. Introduced in C++11.
      char32_t l = U'D';
  4. Boolean Type
    • bool: Represents boolean values (true or false).
      bool m = true;

Derived Data Types

  1. Arrays
    • A collection of elements of the same type stored in contiguous memory locations.
      int arr[5] = {1, 2, 3, 4, 5};
  2. Pointers
    • Variables that store memory addresses of other variables.
      int n = 10;
      int* ptr = &n;
  3. References
    • An alias for another variable.
      int o = 20;
      int& ref = o;
  4. Functions
    • Blocks of code that perform specific tasks.
      int add(int p, int q){
      return p + q;
      }

User-Defined Data Types

  1. Structures (struct)
    • Collections of variables under one name, which can be of different types.
      struct Person {
      std::string name;
      int age;
      };
  2. Unions
    • Similar to structures, but all members share the same memory location.
      union Data {
      int intVal;
      float floatVal;
      };
  3. Enumerations (enum)
    • A user-defined type consisting of a set of named integral constants.
      enum Color { RED, GREEN, BLUE };
  4. Classes
    • Extends the concept of structures by adding member functions and providing access control (public, private, protected).
      class Car {
      public:
      std::string model;
      int year;
      void start(){
      // code to start the car

      }
      };

Typedefs and Aliases

  • typedef: Used to create an alias for a data type.
    typedef unsigned long ulong;
  • using: Modern way to create type aliases.
    using ulong = unsigned long;

C++ Type Modifiers

a tabular representation of C++ type modifiers, which are used to alter the properties of basic data types to suit various needs.

Modifier Description Example
signed Default for integer types, allows storing both positive and negative values. signed int a = -1;
unsigned Only allows non-negative values, effectively doubling the upper range for positive values. unsigned int b = 5;
short Typically uses less memory than int, often 2 bytes. short c = 100;
long Uses more memory than int, typically 4 or 8 bytes. long d = 100000L;
long long Even larger than long, typically 8 bytes. long long e = 1000000000LL;
const Declares a constant value that cannot be modified after initialization. const int f = 10;
volatile Tells the compiler that the value of the variable may change at any time, preventing optimization. volatile int g;
restrict Indicates that a pointer is the only means by which the object it points to can be accessed. (C99, C++) int * restrict ptr;
mutable Allows a member of an object to be modified even if the object is declared const. mutable int h;
constexpr Specifies that the value of a variable or function can be evaluated at compile-time. constexpr int i = 5;

Detailed Examples

  • unsigned:
    unsigned int age = 25; // Can only hold non-negative values
  • short:
    short int temperature = -15; // Smaller range but less memory usage
  • long:
    long distance = 1234567890L; // Larger range than int
  • const:
    const double pi = 3.14159; // Value cannot be changed after initialization
  • volatile:
    volatile int timer; // Value may change unexpectedly, e.g., in embedded systems
  • mutable:
    class Example {
    public:
    int value;
    mutable int counter; // Can be modified even in a const object
    };
    const Example ex = {10, 0};
    ex.counter++;
    // Allowed because counter is mutable
  • constexpr:
    constexpr int square(int x){
    return x * x;
    }
    constexpr int result = square(5); // Computed at compile-time

C++ Constants

In C++, constants are values that do not change during the execution of a program. Constants are useful for defining values that should remain constant throughout the program’s lifecycle, improving code readability and maintainability. Here is an overview of different ways to define constants in C++:

Types of Constants

  1. Literal Constants
  2. const Keyword
  3. constexpr Keyword
  4. Enumerations (enum)
  5. #define Preprocessor Directive

1. Literal Constants

These are the most basic form of constants, directly represented by their values in the code.

  • Integer Literals:
    int age = 30;
  • Floating-Point Literals:
    double pi = 3.14159;
  • Character Literals:
    char newline = '\n';
  • String Literals:
    const char* greeting = "Hello, World!";

2. const Keyword

The const keyword is used to define variables whose values cannot be modified after initialization.

  • Constant Variable:
    const int max_users = 100;
  • Constant Pointer to Variable:
    int value = 10;
    const int* ptr = &value; // Pointer to a constant integer
  • Pointer to a Constant Variable:
    int* const ptr2 = &value; // Constant pointer to an integer

3. constexpr Keyword

Introduced in C++11, constexpr ensures that the value of a variable is evaluated at compile time, making it more powerful than const for certain scenarios.

  • Compile-Time Constant:
    constexpr int square(int x){
    return x * x;
    }
    constexpr int result = square(5); // Evaluated at compile time

4. Enumerations (enum)

Enumerations are a way to define a set of named integral constants, which can make code more readable.

  • Simple Enum:
    enum Color { RED, GREEN, BLUE };
    Color myColor = RED;
  • Enum Class (Scoped Enum):
    enum class Direction { NORTH, EAST, SOUTH, WEST };
    Direction myDirection = Direction::NORTH;

5. #define Preprocessor Directive

The #define directive is used to define constants and macros. It is a preprocessor directive and does not provide type safety.

  • Macro Constant:
    #define PI 3.14159
  • Macro with Parameters:
    #define SQUARE(x) ((x) * (x))

Comparison and Usage

  • Literal Constants: Simple and direct, but can make code less readable if overused.
  • const Keyword: Preferred for constant variables, offers type safety and better readability.
  • constexpr Keyword: Useful for compile-time constant expressions, offering performance benefits.
  • Enumerations: Enhance readability and safety for sets of related constants.
  • #define Directive: Powerful, but less preferred due to lack of type safety and potential for macro-related bugs.

Examples in Code

#include <iostream>
constexpr int getFive(){
return 5;
}
enum class Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };
#define AREA_OF_CIRCLE(radius) (PI * (radius) * (radius))
#define PI 3.14159
int main(){
const int maxAttempts = 3;
constexpr int compileTimeConst = getFive();
Day today = Day::WEDNESDAY;
std::cout << "Max attempts: " << maxAttempts << std::endl;
std::cout << "Compile time constant: " << compileTimeConst << std::endl;
int radius = 10;
double area = AREA_OF_CIRCLE(radius);
std::cout << "Area of circle: " << area << std::endl;
return 0;
}

C++ Operators

1. C++ Arithmetic Operators

Operator Description
+ Addition
Subtraction
* Multiplication
/ Division
% Modulus (Remainder)

In C++, arithmetic operators are symbols used to perform mathematical operations on variables or values. Here are the basic arithmetic operators in C++:

  1. Addition (+): Adds two operands.
  2. Subtraction (-): Subtracts the right operand from the left operand.
  3. Multiplication (*): Multiplies two operands.
  4. Division (/): Divides the left operand by the right operand.
  5. Modulus (%): Divides the left operand by the right operand and returns the remainder.

Example:

#include <iostream>
using namespace std;
int main(){
int a = 10;
int b = 4;
int result;
// Addition

result = a + b;
cout << "Addition: " << result << endl;
// Subtraction

result = a - b;
cout << "Subtraction: " << result << endl;
// Multiplication

result = a * b;
cout << "Multiplication: " << result << endl;
// Division
result = a / b;
cout << "Division: " << result << endl;
// Modulus
result = a % b;
cout << "Modulus: " << result << endl;

return 0;

}

Output:

Addition: 14
Subtraction: 6
Multiplication: 40
Division: 2
Modulus: 2
2. C++ Assignment Operators
Operator Description
= Assigns the value on the right to the variable on the left.
+= Adds the value on the right to the variable on the left and assigns the result to the variable on the left.
-= Subtracts the value on the right from the variable on the left and assigns the result to the variable on the left.
*= Multiplies the variable on the left by the value on the right and assigns the result to the variable on the left.
/= Divides the variable on the left by the value on the right and assigns the result to the variable on the left.
%= Divides the variable on the left by the value on the right and assigns the remainder to the variable on the left.

In C++, assignment operators are used to assign values to variables. Here are the basic assignment operators in C++:

  1. Assignment (=): Assigns the value on the right to the variable on the left.
  2. Addition assignment (+=): Adds the value on the right to the variable on the left and assigns the result to the variable on the left.
  3. Subtraction assignment (-=): Subtracts the value on the right from the variable on the left and assigns the result to the variable on the left.
  4. Multiplication assignment (*=): Multiplies the variable on the left by the value on the right and assigns the result to the variable on the left.
  5. Division assignment (/=): Divides the variable on the left by the value on the right and assigns the result to the variable on the left.
  6. Modulus assignment (%=): Divides the variable on the left by the value on the right and assigns the remainder to the variable on the left.

Example:

#include <iostream>
using namespace std;
int main(){
int a = 10;
int b = 4;
// Assignment
int result = a;
cout << "Assignment: " << result << endl;
// Addition
assignment
result += b;
cout << "Addition assignment: " << result << endl;
// Subtraction
assignment
result -= b;
cout << "Subtraction assignment: " << result << endl;
// Multiplication
assignment
result *= b;
cout << "Multiplication assignment: " << result << endl;
// Division
assignment
result /= b;
cout << "Division assignment: " << result << endl;
// Modulus
assignment
result %= b;
cout << "Modulus assignment: " << result << endl;

return 0;

}

Output:

Assignment: 10
Addition assignment: 14
Subtraction assignment: 10
Multiplication assignment: 40
Division assignment: 10
Modulus assignment: 2

3. C++ Relational Operators

In C++, relational operators are used to compare two values and determine the relationship between them. Here are the common relational operators in C++:

  1. Equal to (==): This operator checks if two values are equal. It returns true if the values are equal, otherwise false.
    int a = 5;
    int b = 5;
    if (a == b)
    {
    // Code executes if a is equal to b

    }
  2. Not equal to (!=): This operator checks if two values are not equal. It returns true if the values are different, otherwise false.
    int a = 5;
    int b = 10;
    if (a != b)
    {
    // Code executes if a is not equal to b

    }
  3. Greater than (>): This operator checks if the value on the left side is greater than the value on the right side. It returns true if the left value is greater, otherwise false.
    int a = 10;
    int b = 5;
    if (a > b)
    {
    // Code executes if a is greater than b

    }
  4. Less than (<): This operator checks if the value on the left side is less than the value on the right side. It returns true if the left value is less, otherwise false.
    int a = 5;
    int b = 10;
    if (a < b)
    {
    // Code executes if a is less than b

    }
  5. Greater than or equal to (>=): This operator checks if the value on the left side is greater than or equal to the value on the right side. It returns true if the left value is greater or equal, otherwise false.
    int a = 10;
    int b = 10;
    if (a >= b) {
    // Code executes if a is greater than or equal to b
    }
  6. Less than or equal to (<=): This operator checks if the value on the left side is less than or equal to the value on the right side. It returns true if the left value is less than or equal, otherwise false.
    int a = 5;
    int b = 10;
    if (a <= b) {
    // Code executes if a is less than or equal to b

    }
Operator Description Example
== (Equal to) Checks if two values are equal. a == b (true if a equals b)
!= (Not equal to) Checks if two values are not equal. a != b (true if a is not b)
> (Greater than) Checks if the left value is greater than the right value. a > b (true if a is greater than b)
< (Less than) Checks if the left value is less than the right value. a < b (true if a is less than b)
>= (Greater than or equal to) Checks if the left value is greater than or equal to the right value. a >= b (true if a is greater than or equal to b)
<= (Less than or equal to) Checks if the left value is less than or equal to the right value. a <= b (true if a is less than or equal to b)

4. C++ Logical Operators

In C++, logical operators are used to perform logical operations on boolean expressions. Here are the logical operators available in C++:

  1. Logical AND (&&): Returns true if both operands are true, otherwise, it returns false.
bool result = (true && false);
// result is false
  1. Logical OR (||): Returns true if at least one of the operands is true, otherwise, it returns false.
bool result = (true || false);
// result is true
  1. Logical NOT (!): Returns true if the operand is false, and returns false if the operand is true.
bool result = !true;
// result is false
Operator Description Example Result
&& Logical AND true && false false
` ` Logical OR
! Logical NOT !true false

5. C++ Bitwise Operators

Bitwise operators in C++ are used to perform operations at the bit level on integers. There are six bitwise operators in C++:

  1. Bitwise AND (&): Performs a bitwise AND operation on each pair of corresponding bits. The result is 1 if both bits are 1, otherwise, it’s 0.
  2. Bitwise OR (|): Performs a bitwise OR operation on each pair of corresponding bits. The result is 1 if at least one of the bits is 1.
  3. Bitwise XOR (^): Performs a bitwise exclusive OR operation on each pair of corresponding bits. The result is 1 if the bits are different, otherwise, it’s 0.
  4. Bitwise NOT (~): Unary operator which flips the bits, i.e., changes 1 to 0 and 0 to 1.
  5. Left Shift (<<): Shifts the bits of the left operand to the left by a number of positions specified by the right operand. The vacated bits are filled with zeros.
  6. Right Shift (>>): Shifts the bits of the left operand to the right by a number of positions specified by the right operand. The vacated bits depend on whether the left operand is signed or unsigned.

techbloggerworld.com

šŸ’» Tech l Career l startup l Developer| Job šŸ“Bangalore, KA šŸ“© work: n4narendrakr@gmail.com šŸŽ“ Ex-SDE intern at Airtel

Leave a Reply

Your email address will not be published. Required fields are marked *