0% found this document useful (0 votes)
14 views10 pages

Intro To C++ Notes

Uploaded by

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

Intro To C++ Notes

Uploaded by

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

Functions in C++

Tokens

Keywords

● Definition: Keywords are predefined, reserved words that form the syntax and
control the behavior of the language. They are fundamental to the language structure
and cannot be used for other purposes.
● Characteristics:
○ Fixed Meaning: Each keyword has a specific, unchanging meaning in C++.
○ Syntax Enforcement: Keywords enforce certain syntax rules and dictate the
structure of statements and declarations in C++.
● Examples:
○ int: Declares integer type variables or functions.
○ class: Declares a class, which is a blueprint for creating objects.
○ public: Specifies that members following this keyword are accessible from
outside the class.
○ private: Specifies that members following this keyword are accessible only
within the class.
● Usage: Keywords are used to define data types, control flow, and other core aspects
of programming. For instance, return is used to exit a function and optionally return
a value to the caller.

Identifiers

● Definition: Identifiers are user-defined names used to identify variables, functions,


arrays, and other entities in C++.
● Characteristics:
○ Naming Rules:
■ Start with a letter (A-Z, a-z) or an underscore (_).
■ Followed by letters, digits (0-9), or underscores.
■ Cannot be a keyword.
○ Uniqueness: Identifiers must be unique within their scope (e.g., local scope,
class scope).
● Examples:
○ counter, maxValue, calculateSum, MyClass.
● Usage: Identifiers help in giving meaningful names to program components, making
the code more readable and easier to maintain.

Constants

● Definition: Constants represent fixed values that do not change during program
execution. They provide a way to use meaningful names for immutable values.
● Characteristics:
○ Literal Constants: Directly used values in the code.
■ Numeric Literals: 10, 3.14, -5.
■ Character Literals: 'a', '1'.
■ String Literals: "Hello", "World".
○ Constant Variables: Declared using the const keyword to prevent
modification after initialization.
○ Example:
cpp
Copy code
const int DAYS_IN_WEEK = 7;

● Usage: Constants prevent accidental changes to values and improve code clarity.
For instance, using const for mathematical constants or fixed configuration values
ensures they remain unchanged throughout the program.

Operators

● Definition: Operators are symbols used to perform operations on operands. They


are fundamental to performing calculations and manipulations in a program.
● Types:
○ Arithmetic Operators: Perform basic mathematical operations.
■ + (addition): Adds two operands.
■ - (subtraction): Subtracts one operand from another.
■ * (multiplication): Multiplies two operands.
■ / (division): Divides one operand by another.
■ % (modulus): Returns the remainder of division.
○ Relational Operators: Compare values and return a boolean result.
■ == (equal to): Checks if two values are equal.
■ != (not equal to): Checks if two values are not equal.
■ > (greater than): Checks if one value is greater than another.
■ < (less than): Checks if one value is less than another.
■ >= (greater than or equal to): Checks if one value is greater than or
equal to another.
■ <= (less than or equal to): Checks if one value is less than or equal to
another.
○ Logical Operators: Used for logical operations, combining boolean values.
■ && (logical AND): Returns true if both operands are true.
■ || (logical OR): Returns true if at least one operand is true.
■ ! (logical NOT): Returns true if the operand is false, and vice
versa.
○ Bitwise Operators: Perform bit-level operations on integer data types.
■ & (bitwise AND): Performs a bitwise AND operation.
■ | (bitwise OR): Performs a bitwise OR operation.
■ ^ (bitwise XOR): Performs a bitwise XOR operation.
■ ~ (bitwise NOT): Inverts all bits.
■ << (left shift): Shifts bits to the left.
■ >> (right shift): Shifts bits to the right.
○ Conditional (Ternary) Operator: A shorthand for if-else statements.
cpp
Copy code
condition ? expression1 : expression2;

■Usage: Provides a concise way to return one of two values based on
a condition.
○ Comma Operator: Allows multiple expressions to be evaluated in a single
statement, with the result being the value of the last expression.
cpp
Copy code
int result = (x = 5, y = 10, x + y); // Evaluates to 15

Scope Resolution Operator

● Definition: The :: operator is used to specify the scope of identifiers, especially to


resolve ambiguities between global and local variables or to define class methods
outside their class definition.
● Usage:
○ Global Scope: To access a global variable when a local variable has the
same name.
cpp
Copy code
int value = 10; // Global variable

○ void display() {
○ int value = 20; // Local variable
○ cout << ::value; // Accesses global variable
○ }

○ Class Member Functions: To define a member function outside the class
definition.
cpp
Copy code
class MyClass {
○ public:
○ void show(); // Declaration
○ };

○ void MyClass::show() {
○ cout << "Show method of MyClass" << endl;
○ }

Expressions and Their Types

● Definition: An expression is a combination of variables, constants, operators, and


functions that evaluates to a single value. Expressions are fundamental to performing
operations and calculations in C++.
● Types:
○ Arithmetic Expressions: Perform arithmetic calculations. They may involve
basic or complex operations.
cpp
Copy code
int result = a + b * c;

○ Relational Expressions: Compare values and result in a boolean value.
cpp
Copy code
bool isEqual = (a == b);

○ Logical Expressions: Combine boolean values using logical operators to
make decisions or control program flow.
cpp
Copy code
bool isValid = (a > b && c < d);

○ Bitwise Expressions: Perform bit-level operations on integer data types,
useful in low-level programming.
cpp
Copy code
int bitwiseResult = a & b; // Bitwise AND

Special Assignment Expressions

● Definition: Special assignment expressions are shorthand notations that combine an


assignment with another operation, providing a concise way to perform common
operations.
● Types:
○ Addition Assignment: Adds the right-hand operand to the left-hand variable.
cpp
Copy code
x += 10; // Equivalent to x = x + 10;

○ Subtraction Assignment: Subtracts the right-hand operand from the
left-hand variable.
cpp
Copy code
x -= 5; // Equivalent to x = x - 5;

○ Multiplication Assignment: Multiplies the left-hand variable by the
right-hand operand.
cpp
Copy code
x *= 2; // Equivalent to x = x * 2;

○ Division Assignment: Divides the left-hand variable by the right-hand
operand.
cpp
Copy code
x /= 4; // Equivalent to x = x / 4;

Function Prototyping

● Definition: Function prototyping involves declaring a function's signature before its


actual definition. It informs the compiler about the function's name, return type, and
parameters, allowing for type checking during function calls.
○ Syntax:
cpp
Copy code
returnType functionName(parameterType1, parameterType2,
...);

● Importance:
○ Type Checking: Ensures that function calls match the function definition in
terms of parameter types and return type.
○ Code Organization: Allows for better organization of code, especially in large
projects where functions may be defined in separate files or sections.
○ Example:
cpp
Copy code
int add(int, int); // Function prototype

○ int main() {
○ int result = add(5, 10);
○ cout << result;
○ return 0;
○ }

○ int add(int a, int b) {
○ return a + b;
○ }

Call by Reference

● Definition: Passing arguments by reference involves passing the address of a


variable to a function. This allows the function to modify the original variable's value,
as opposed to passing by value, which only gives the function a copy of the variable.
○ Syntax:
cpp
Copy code
void modifyValue(int &x) {
○ x = 20; // Modifies the original variable
○ }

● Advantages:
○ Efficiency: Passing large data structures or objects by reference avoids the
overhead of copying them, which can improve performance.
○ Modification: Allows functions to modify the actual variables passed in, not
just copies.
○ Example:
cpp
Copy code
int main() {
○ int num = 10;
○ modifyValue(num);
○ cout << num; // Prints 20
○ return 0;
○ }

○ void modifyValue(int &x) {
○ x = 20;
○ }

Function Overloading

● Definition: Function overloading allows multiple functions with the same name but
different parameter lists to coexist in the same scope. The appropriate function is
chosen based on the arguments provided during the function call.
● Rules:
○ Different Parameters: Functions must differ in the number or type of
parameters (or both).
○ Same Scope: Overloaded functions must be in the same scope (e.g., within
the same class or namespace).
● Usage:
○ Enhanced Readability: Provides a way to perform similar operations with
different types or numbers of arguments using the same function name.
○ Example:
cpp
Copy code
void print(int i) {
○ cout << "Integer: " << i << endl;
○ }

○ void print(double d) {
○ cout << "Double: " << d << endl;
○ }

○ void print(string s) {
○ cout << "String: " << s << endl;
○ }

Default Arguments

● Definition: Default arguments allow functions to be called with fewer arguments than
specified. If arguments are omitted, default values are used.
○ Syntax:
cpp
Copy code
void greet(string name = "Guest", string salutation =
"Hello") {
○ cout << salutation << ", " << name << "!" << endl;
○ }

● Usage:
○ Flexibility: Provides the ability to call functions with varying numbers of
arguments, offering more flexibility in function usage.
○ Example:
cpp
Copy code
int main() {
○ greet(); // Uses default values
○ greet("Alice"); // Uses default salutation
○ greet("Bob", "Hi"); // No default values used
○ return 0;
○ }

Inline Functions

● Definition: Inline functions are small functions that are defined with the inline
keyword. The compiler attempts to insert the function’s code directly at the point of
each call to reduce function call overhead.
● Usage:
○ Performance: Suitable for small, frequently called functions where function
call overhead might impact performance.
○ Syntax:
cpp
Copy code
inline int square(int x) {
○ return x * x;
○ }

● Considerations:
○ Size of Function: Inline functions are typically used for short functions. Large
functions might increase the size of the binary and negatively affect
performance.
○ Compilation: The inline keyword is a suggestion to the compiler, which
may choose to ignore it based on its own optimization strategies.

Recursive Functions

● Definition: A recursive function is one that calls itself to solve a problem. Recursive
functions are typically used for problems that can be divided into smaller, similar
subproblems.
● Characteristics:
○ Base Case: The condition under which the function stops calling itself. It
prevents infinite recursion.
○ Recursive Case: The part where the function calls itself with modified
arguments to move towards the base case.
○ Example:
cpp
Copy code
int factorial(int n) {
○ if (n <= 1) return 1; // Base case
○ else return n * factorial(n - 1); // Recursive case
○ }

Function Templates

● Definition: Function templates allow the creation of functions that can operate with
any data type. They enable generic programming by defining functions with type
parameters.
○ Syntax:
cpp
Copy code
template <typename T>
○ T max(T a, T b) {
○ return (a > b) ? a : b;
○ }

● Usage:
○ Generic Programming: Allows functions to handle different data types with a
single definition, reducing code duplication.
○ Example:
cpp
Copy code
int main() {
○ cout << max(10, 20) << endl; // Uses int
○ cout << max(3.14, 2.71) << endl; // Uses double
○ return 0;
○ }

Lambda Functions

● Definition: Lambda functions are anonymous functions that can be defined inline
without a name. They are useful for short-term, one-off functions and are often used
with algorithms.
○ Syntax:
cpp
Copy code
[capture](parameters) -> returnType { body }

● Usage:
○ Local Scope: Ideal for functions that are used only within a limited scope,
such as a specific function call.
○ Capture List: Allows the lambda to capture variables from its surrounding
scope.
○ Example:
cpp
Copy code
int main() {
○ auto add = [](int a, int b) -> int {
○ return a + b;
○ };
○ cout << add(5, 10) << endl; // Prints 15
○ return 0;
● }

You might also like