0% found this document useful (0 votes)
12 views

C++

C++ is a powerful programming language developed by Bjarne Stroustrup in 1983, known for its object-oriented features and efficiency in performance-critical applications like games and operating systems. It supports both procedural and object-oriented programming, with a rich set of libraries and tools for development. The document outlines C++ syntax, memory management, data types, and the execution model, providing a comprehensive overview for beginners and experienced programmers alike.

Uploaded by

veer metri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C++

C++ is a powerful programming language developed by Bjarne Stroustrup in 1983, known for its object-oriented features and efficiency in performance-critical applications like games and operating systems. It supports both procedural and object-oriented programming, with a rich set of libraries and tools for development. The document outlines C++ syntax, memory management, data types, and the execution model, providing a comprehensive overview for beginners and experienced programmers alike.

Uploaded by

veer metri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

C++ Programming Language

C++ is a programming language used to create software, games, and applications. It is


an extension of the C language with added features like object-oriented
programming (using classes and objects).
Key points:
 Developed by: Bjarne Stroustrup in 1983.
 Fast and powerful, used for performance-critical applications.
 Commonly used for game development, operating systems, and software
development.
Why use C++?
C++ is used because it is fast and efficient, supports object-oriented programming,
offers low-level memory control, and is versatile for developing games, operating
systems, and high-performance applications. It also has rich library support and is
widely used in legacy systems.
C vs C++
C is a procedural language, while C++ is both procedural and object-oriented,
offering features like classes and objects. C focuses on low-level programming and is
widely used for embedded systems. C++ adds features like inheritance,
polymorphism, and abstraction, making it better for complex applications like
games and GUIs. Additionally, C++ provides dynamic memory management and the
Standard Template Library (STL) for ready-to-use data structures, which C lacks.
In short, C is closer to hardware, and C++ is more versatile for advanced
programming needs.
C++ Development Tools
- IDE (Integrated Development Tool)- for Windows(VS Code, Microsoft Visual
Studio, CodeLite, etc.), for Linux(VS Code, Qt Creator, CodeLite), for MAC(VS Code,
Xcode, CodeLite).
- Compiler - A compiler in C++ is a program that translates C++ code into machine
code so it can be executed by a computer.
Ex > Windows(Mingw-Gcc, Msvc, Clang llvm) Linux(Gcc, Clang llvm) MAC(Gcc,
Clang Apple, Clang llvm)
Installing Compilers
1. Google Search: Search for "Winlibs".
2. Download: Download the latest release version (e.g., GCC 11.2.0) compatible
with your system architecture (Win32/Win64) as a ZIP file.
3. Extract: Extract the ZIP file (e.g., mingw64) to your preferred location. It is
recommended to extract it to Local Disk C (e.g., C:\mingw64).
4. Copy Path: Navigate to the bin folder inside mingw64 (e.g., C:\mingw64\bin)
and copy its path.
5. Set Environment Variable:
a. Open Environment Variables settings on your system.
b. Find the Path variable under System Variables and click Edit.
c. Paste the copied path (C:\mingw64\bin) into the list and save the
changes.

Libraries
A library in C++ is a collection of precompiled code (functions, classes, or objects) that
you can use in your program to save time and avoid rewriting common functionalities.
C++ Program Structure
#include <iostream>
int main(){
std::cout << “Hello World!”<<std::endl;
std::cout<< “Welcome to C++ Programming World” ;
std:: cin<< “Enter Your Name: ”;
return 0;
}
Explanation
#include <iostream> : is a directive that includes the Input/Output Stream library in
your program, enabling you to use functionalities like std::cout for output and std::cin
for input.
int main(): is the entry point of a C++ program. When the program runs, it starts
execution from the main function. Here's what it does:
1. int part: It means the function returns an integer value to the operating system
after execution. Typically, returning 0 means the program ran successfully.
2. main() part: This is the function name where your program starts. You put your
program’s logic inside the curly braces { }.
std::cout: Used to display output on the console.
std::cin: Used to take input from the user.
std::endl: Moves to a new line and flushes the output buffer.

Namespace:
✅ Namespaces organize code and avoid conflicts.
✅ Use using namespace carefully to avoid accidental name clashes.
✅ Use nested namespaces to structure code in large projects.
✅ Anonymous namespaces help hide implementation details.
✅ Aliases simplify long namespace names.
1 Declaring a Namespace
1️⃣
namespace Math {
int add(int a, int b) {
return a + b;
}
}

2️⃣Accessing Namespace Members

std::cout << Math::add(3, 5); // Output: 8

 Using scope resolution operator (::):

using namespace Math;


std::cout << add(3, 5); // No need to write Math::

namespace Outer {
namespace Inner {
void display() {
std::cout << "Inside Inner Namespace";
}
}
}
Outer::Inner::display(); // Accessing function

namespace M = Math; // Alias


std::cout << M::add(2, 3); // Using alias

Using namespace directive (using namespace):


⚠️Avoid using namespace std; in large projects to prevent conflicts.
3️⃣Nested Namespaces
4️⃣Namespace Aliases (Short Names)
5️⃣Anonymous (Unnamed) Namespaces
🔹 Used for private scope within a file (similar to static in C).

Comments
// Comments out a single line
/* … */ Block comments out a block of text
/* … */ Block comments can’t be nested

Errors and Warnings


Compile-time Errors: Errors detected by the compiler while converting source code
into machine code, like syntax or type errors.
Runtime Errors: Errors that occur during the execution of a program, causing it to
crash or behave unexpectedly.
Warnings: Non-critical issues flagged by the compiler that won't stop the code from
running but might lead to potential problems.
Statements
A statement is basic unit of computation in a c++ program. Every C++ program is a
collection of statements organized in a certain way to achieve some goal. Statements end
with a semicolon in c++ (;).
Statement are executed in order from top to bottom when the program is run.
Execution keeps going until the program ends.

Functions
A function in C++ is a block of code that performs a specific task and can be reused
multiple times. Function must be defined before it’s use.
Reduces code duplication (write once, use multiple times).
Improves readability and modularity of code.
Can take input (parameters) and return output (return value).

Syntax:
namespace function_name(parameters)
return_type { {
int secretValue = 42; // Can only
// Function body (code to execute) be accessed in this file
}return value; // If return_type is not void
std::cout << secretValue;
}

Example:

int add(int a, int b) {


return a + b;
}
Input Output
Stream Purpose
std::cou Printing data to the console(terminal)
t
std::cin Reading data from terminal
std::cerr Printing errors to the console
std::clog Printing log messages to the console.

Chaining std::cin

std::cin>>a>>b;

reading data with spaces


we can read the data with space by the getline method().
Syntax:
std::getline(std::cin, var_name)

String
A string in C++ is a sequence of characters used to store and manipulate text.
To use string we need include the library called string as #include <string>
In C++, there are two main ways to handle strings:
1. C-style strings (char arrays)
2. std::string (Preferred, Modern C++ approach)
C-style Strings (Old way)
C-style strings are character arrays ending with a null terminator \0.

#include <iostream>

int main() {
char str[] = "Hello";
std::cout << str << std::endl;
return 0;
}
1️⃣Getting the Length of a String
We use .length() or .size() to get the number of characters in a string.

#include <iostream>
#include <string>

int main() {
std::string message = "C++ is awesome!";
std::cout << "Length: " << message.length() << std::endl;
std::cout << "Size: " << message.size() << std::endl; // Same as length()
return 0;
}

📌 Note: .length() and .size() do the same thing.


2️⃣Accessing Characters in a String
We can access individual characters in two ways:
 Using [] (Bracket notation)
 Using .at() function (Safer way)

#include <iostream>
#include <string>

int main() {
std::string word = "Hello";

// Using []
std::cout << "First letter: " << word[0] << std::endl;

// Using .at()
std::cout << "Last letter: " << word.at(word.length() - 1) << std::endl;

return 0;
}

📌 Difference:
 word[0] works but does not check bounds.
 word.at(0) is safer because it throws an error if the index is out of range.

3️⃣Modifying Strings
We can append, insert, and erase characters in a string.
📌 a) Appending to a String (+= and .append())

#include <iostream>
#include <string>

int main() {
std::string greeting = "Hello";
// Using +=
greeting += ", World!";
// Using .append()
greeting.append(" How are you?");
std::cout << greeting << std::endl;

return 0;
}

#include <iostream>
#include <string>

int main() {
std::string greeting = "Hello";
// Using +=
greeting += ", World!";
// Using .append()
greeting.append(" How are you?");

std::cout << greeting << std::endl;

return 0;
}

📌 b) Inserting into a String (.insert())

#include <iostream>
#include <string>

int main() {
std::string sentence = "I love programming!";
// Erase "love " (index 2, length 5)
sentence.erase(2, 5);
std::cout << sentence << std::endl;
return 0;
}

📌 c) Erasing from a String (.erase())


4️⃣Finding a Substring using .find(), rfind()
We use .find(substring) to locate a word in a string. It returns the position (index) of
the first occurrence or std::string::npos if not found.
If a word appears multiple times, .rfind() searches from the right (end) instead of the

#include <iostream>
#include <string>

int main() {
std::string text = "Programming in C++ is fun fun!";

size_t pos = text.find("C++"); // Find "C++"


size_t pos1 text.rfind(“fun”);

if (pos != std::string::npos) { // Check if found


std::cout << "\"C++\" found at index: " << pos << std::endl;
} else {
std::cout << "\"C++\" not found!" << std::endl;
}

return 0;
}
left.

📌 Note: std::string::npos is a constant that represents "not found."


5️⃣Replacing a Substring using .replace()
The .replace(pos, length, newString) function replaces part of a string.

#include <iostream>
#include <string>

int main() {
std::string sentence = "The quick brown fox jumps over the lazy dog.";

size_t pos = sentence.find("brown ");


if (pos != std::string::npos) {
sentence.erase(pos, 6); // Remove "brown "
}

std::cout << sentence << std::endl;

return 0;
}

6️⃣Removing a Word Dynamically


We can find a word first and then remove it using .erase().

#include <iostream>
#include <string>

int main() {
std::string phrase = "I hate Mondays!";

// Replace "hate" with "love"


size_t pos = phrase.find("hate");
if (pos != std::string::npos) {
phrase.replace(pos, 4, "love");
}

std::cout << phrase << std::endl;

return 0;
}
Execution Model
The C++ execution model defines how a program is compiled, linked, and executed.
Stages of Execution
1. Preprocessing
o Removes comments, expands macros, and includes header files.
2. Compilation
o Converts source code (.cpp) into assembly code.
3. Assembly
o Converts assembly code into machine code (.obj or .o).
4. Linking
o Combines object files and libraries into an executable (.exe).
5. Loading
o Loads the executable into memory for execution.
6. Execution (Runtime)
o CPU executes instructions, manages memory, and handles I/O.

2. Memory Model in C++


The C++ memory model defines how memory is allocated and managed during
execution.
Memory Layout in C++
1. Code Segment (Text Segment)
o Stores the compiled program instructions.
2. Data Segment
o Stores global & static variables.
o Divided into:
 Initialized Data (variables with initial values).
 Uninitialized Data (BSS) (variables without initial values).
3. Heap
o Stores dynamically allocated memory (via new/malloc).
o Must be manually deallocated (delete/free).
4. Stack
o Stores local variables, function calls, and return addresses.
o Follows LIFO (Last In, First Out) order.
C++ Core Language, Standard Library & STL
1. C++ Core Language
The core language consists of:
✅ Syntax & Semantics (variables, loops, conditions, functions)
✅ Memory Management (new/delete, pointers, references)
✅ Object-Oriented Programming (OOP) (classes, inheritance, polymorphism)
✅ Templates & Exception Handling
2. C++ Standard Library
The Standard Library provides pre-written functions & classes to simplify coding.
🔹 I/O Stream (iostream) – Input/Output handling
🔹 String Handling (string) – String manipulation
🔹 Math Functions (cmath) – Math operations like sqrt(), pow()
🔹 Time Functions (ctime) – Time & date utilities

3. Standard Template Library (STL)


The STL provides ready-to-use templates for data structures & algorithms.
📌 Containers – Store & manage data
 vector, list, map, set, queue, stack
📌 Algorithms – Sorting, searching, etc.
 sort(), find(), binary_search()
📌 Iterators – Access elements in containers
📌 Functors – Function objects used in algorithms

Variables and Data Types


Variables in C++
A variable is a named storage location in memory that holds a value.
Syntax
data_type variable_name = value;
2. Data Types in C++
Datatype Modifiers:
As the name implies, datatype modifiers are used with built-in data types to modify
the length of data that a particular data type can hold. Data type modifiers in C++
are:
 signed
 unsigned
 short
 long
Const:
const (constant) variables cannot be changed by your program during execution.
C++ has different data types based on the kind of value stored.
Data Size Example Usage
Type
int 4 bytes int x = 10; Whole numbers
float 4 bytes float y = 5.67; Decimal numbers
double 8 bytes double z = 3.14159; High-precision decimals
char 1 byte char c = 'A'; Single characters
bool 1 byte bool isOn = true; True (1) or False (0)
string Varies string name = "Alice"; Text (requires <string>)

3. Special Data Types


 void → No value (used for functions)
 auto → Automatically detects data type
 long & short → Modifies integer size
 unsigned → Only positive values
📌 Example:
auto num = 42; // Automatically detects as int
unsigned int positive = 100; // No negative values

Number Digits Prefix in Decimal


System Base Used C++ Example Equivalent
Decimal 10 0-9 None int num = 25; 25
int binNum =
Binary 2 0, 1 0b 0b1010; 10
int octNum =
Octal 8 0-7 0 012; 10
int hexNum =
Hexadecimal 16 0-9, A-F 0x 0xA; 10
Variable Initialization
Type Syntax Key Points
Assignment int x = Simple and intuitive, but less safe in modern C++.
10;
Functional int Works for objects and primitive types but lacks
x(10); consistency with complex types.
Brace int Modern and safe, prevents narrowing conversions,
(Uniform) x{10}; recommended in C++11+.

sizeof Type in memory


The sizeof operator in C++ is used to determine the size (in bytes) of a data type or
variable in memory.
sizeof(data_type_or_variable);
Integer
An integer is a data type used to store whole numbers (positive, negative, or zero)
without decimal points.
Type Size Range Description
(bytes)
int 4 -2,147,483,648 to 2,147,483,647 Standard integer
type.
short int 2 -32,768 to 32,767 Smaller integer
type.
long int 4 or 8 At least -2,147,483,648 to Larger integer
2,147,483,647 type.
long long 8 -9,223,372,036,854,775,808 to Very large
int 9,223,372,036,854,775,807 integers.
unsigned 4 0 to 4,294,967,295 Stores only
int positive values.

Float
A float is a data type used to store numbers with decimal points or fractional values.
Size
Type Precision Description
(bytes)
float 4 7 decimal places Single-precision floating-
point.
Double-precision
double 8 15 decimal places
floating-point.
long 8, 12, or More than double (platform-
Extended precision.
double 16 dependent)

When we divide the floating point number with 0 then the result will be an infinity
When we divide the floating point 0 with floating point 0 then the result will be
Nan(Not a Number)
Note: When writing floating remember to add suffix to the number (e.g., 9.8f). and also
for long double add suffix
Boolean
Booleans in C++ are represented by the bool type. A bool is either true or false.
C++ supports three boolean operators: ! (NOT), && (AND), and || (OR). You can also
use the alternative versions not, and, and or.
Precedence
The three Boolean operators each have different operator precedence. As a consequence,
they are evaluated in this order:
1. ! Highest precedence
2. && Medium
3. || Low Precedence.
If you want to force a different ordering, you can enclose a Boolean expression in
parentheses (ie. ()), as the parentheses have even higher operator precedence.
std::boolalpha : Changes Boolean output on streams from numeric (1/0) to textual
("true"/"false").
Characters and Text : ASCII Table
char Type:
 Represents a single character (typically 1 byte).
 Example literal: 'A'
Wide Characters:
 wchar_t for wider character sets.
 Use L'A' for wide char literals.
Unicode (C++11+):
 char16_t and char32_t for UTF-16 and UTF-32.
static_cast<data_type>: Convert an expression from one type to another at compile
time, with type safety.
Auto Keyword in C++
 Definition & Purpose
o Introduced in C++11.
o Enables type inference: the compiler deduces a variable's type from its
initializer.
o Simplifies declarations for complex types (e.g., iterators, lambda
expressions).
auto x = 42; // x deduced as int
Assignment Operator
Assignment Operator in C++
 Definition:
o The assignment operator (=) assigns the value of one object (right-hand
side) to another (left-hand side).
o It is used for both built-in and user-defined types.
Operations on datatypes
Arithmetic Operations:

Relational Operator
When writing conditional statements, sometimes we need to use different types of
operators to compare values. These operators are called
Preview: Docs C++ supports different types of operators such as arithmetic, relational,
and logical operators.
To have a condition, we need relational operators:
 == equal to
 != not equal to
 > greater than
 < less than
 >= greater than or equal to
 <= less than or equal to
Relational operators compare the value on the left with the value on the right.

If Statement
An if statement is used to test an expression for truth and execute some code based on
it. Here’s a simple form of the if statement:
Syntax:
if (condition) {
some code
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy