Adv-Keywords With Sample Case Use
Adv-Keywords With Sample Case Use
asm
============================================
#include <iostream>
int main() {
int result;
asm ("movl $5, %0" : "=r"(result)); // Inline assembly to move 5 into
result
std::cout << "Result from assembly: " << result << std::endl;
return 0;
}
The asm keyword allows embedding assembly code within C++ programs for low-level
hardware manipulation.
2. auto
============================================
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
auto allows the compiler to deduce the type of variables, improving code readability and
maintainability.
3. volatile
============================================
#include <iostream>
#include <thread>
#include <chrono>
void setFlag() {
std::this_thread::sleep_for(std::chrono::seconds(1));
flag = true; // Set flag after 1 second
}
int main() {
std::thread t(setFlag);
while (!flag) {
// Busy wait
}
std::cout << "Flag was set!" << std::endl;
t.join();
return 0;
}
volatile informs the compiler that the variable may change unexpectedly, thus preventing it
from optimizing away checks on it.
4. while
============================================
#include <iostream>
int main() {
int number;
std::cout << "Enter numbers (0 to quit): ";
return 0;
}
The while loop continues to execute as long as the condition is true, making it useful for
processing input until a specific condition is met.
5. bool
============================================
#include <iostream>
int main() {
bool isValid = true;
bool hasPermission = false;
return 0;
}
bool is a fundamental type used to represent truth values, enabling logical operations and
conditions.
6. break
============================================
#include <iostream>
int main() {
for (int i = 0; i < 10; ++i) {
std::cout << "Iteration " << i << std::endl;
if (i == 5) {
break; // Exit loop when i is 5
}
}
return 0;
}
break terminates the nearest enclosing loop or switch statement, allowing for controlled
exits.
7. case
============================================
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
default:
std::cout << "Invalid day" << std::endl;
break;
}
return 0;
}
case defines the specific values that a switch variable can take, facilitating cleaner multi-
branch decision-making.
8. catch
============================================
#include <iostream>
#include <stdexcept>
void mightGoWrong() {
throw std::runtime_error("Something went wrong!");
}
int main() {
try {
mightGoWrong();
} catch (const std::runtime_error& e) {
std::cout << "Caught an exception: " << e.what() << std::endl;
}
return 0;
}
catch specifies how to respond to exceptions of specific types, allowing for controlled error
handling.
9. char
============================================
#include <iostream>
int main() {
char name[] = "John Doe";
for (char c : name) {
if (c == ' ') {
std::cout << "Space found!" << std::endl;
} else {
std::cout << c << std::endl; // Print each character
}
}
return 0;
}
char is used to represent single characters or create character arrays, often utilized in string
handling.
10. class
============================================
#include <iostream>
class Rectangle {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() {
return width * height;
}
private:
double width;
double height;
};
int main() {
Rectangle rect(5.0, 3.0);
std::cout << "Area: " << rect.area() << std::endl; // Output: 15
return 0;
}
11. const
============================================
#include <iostream>
int main() {
const int MAX_ITEMS = 100; // Constant value
std::cout << "Max items: " << MAX_ITEMS << std::endl;
return 0;
}
const indicates that a variable’s value cannot be changed after initialization, promoting
safety and clarity.
12. const_cast
============================================
#include <iostream>
int main() {
int x = 10;
printValue(&x);
std::cout << "Modified value: " << x << std::endl; // Output: 100
return 0;
}
const_cast allows casting away the const qualifier, enabling modifications of originally
constant variables.
13. continue
============================================
#include <iostream>
int main() {
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
std::cout << i << " "; // Output: 1 3 5 7 9
}
std::cout << std::endl;
return 0;
}
continue skips the rest of the loop iteration and proceeds to the next one, allowing for
selective processing of loop elements.
14. default
============================================
#include <iostream>
int main() {
int option = 4;
switch (option) {
case 1:
std::cout << "Option 1" << std::endl;
break;
case 2:
std::cout << "Option 2" << std::endl;
break;
default:
std::cout << "Invalid option" << std::endl; // Executes if no
case matches
break;
}
return 0;
}
default specifies the action to take when no case matches in a switch statement, serving as a
fallback option.
15. delete
============================================
#include <iostream>
int main() {
int* ptr = new int(5); // Dynamically allocate an integer
std::cout << "Value: " << *ptr << std::endl;
delete ptr; // Free memory
return 0;
}
delete releases memory allocated with new, preventing memory leaks in dynamic memory
management.
16. do
============================================
#include <iostream>
int main() {
int number;
do {
std::cout << "Enter a positive number (negative to quit): ";
std::cin >> number;
} while (number >= 0);
The do keyword initiates a loop that guarantees at least one execution, useful for user input
validation.
17. double
============================================
#include <iostream>
int main() {
double length = 5.5;
double width = 2.3;
double area = length * width;
std::cout << "Area of rectangle: " << area << std::endl; // Output:
12.65
return 0;
}
double provides greater precision than float, making it suitable for calculations requiring
significant decimal places.
18. dynamic_cast
Using dynamic_cast for safe downcasting in polymorphism:
============================================
#include <iostream>
#include <typeinfo>
class Base {
public:
virtual ~Base() {}
};
int main() {
Base* basePtr = new Derived(); // Base pointer to Derived object
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // Safe
downcasting
if (derivedPtr) {
std::cout << "Successfully downcasted to Derived." << std::endl;
} else {
std::cout << "Downcasting failed." << std::endl;
}
delete basePtr;
return 0;
}
dynamic_cast performs a safe runtime check when downcasting, ensuring that the object is
of the correct type.
19. else
============================================
#include <iostream>
int main() {
int score = 75;
return 0;
}
else provides a fallback option in conditional branching, ensuring that one of the paths is
taken.
20. enum
============================================
#include <iostream>
int main() {
Color favoriteColor = Color::Blue;
switch (favoriteColor) {
case Color::Red:
std::cout << "Favorite color is Red." << std::endl;
break;
case Color::Green:
std::cout << "Favorite color is Green." << std::endl;
break;
case Color::Blue:
std::cout << "Favorite color is Blue." << std::endl; // Output
break;
}
return 0;
}
enum defines a set of named constants, enhancing code readability and maintainability.
21. except
Note: except is not a standard C++ keyword; it may be from another language context. The
closest in C++ is try and catch. I will skip this one unless you need it in a specific context.
22. explicit
============================================
#include <iostream>
class Fraction {
public:
explicit Fraction(int num) : numerator(num), denominator(1) {}
void display() const {
std::cout << numerator << "/" << denominator << std::endl;
}
private:
int numerator;
int denominator;
};
int main() {
Fraction frac(5); // Explicitly constructed
frac.display();
return 0;
}
explicit prevents automatic type conversions, ensuring that constructors are called only
when intended.
23. extern
============================================
#include <iostream>
int main() {
std::cout << "Shared value: " << sharedValue << std::endl; // Uses the
value from another file
return 0;
}
extern is used for variable declarations across multiple files, facilitating linkage in larger
programs.
24. false
============================================
#include <iostream>
int main() {
bool flag = false;
if (!flag) {
std::cout << "Flag is false." << std::endl; // Output
}
return 0;
}
false represents a boolean false value, essential for conditional checks and logical
operations.
25. finally
Note: finally is not a standard C++ keyword. In C++, we typically use RAII principles for
cleanup. I’ll skip this one as well.
26. float
============================================
#include <iostream>
int main() {
float radius = 2.5f;
float area = 3.14f * radius * radius;
std::cout << "Area of circle: " << area << std::endl; // Output: Area
of circle: 19.625
return 0;
}
float is used for single-precision floating-point calculations, suitable for applications where
memory is a concern.
27. for
============================================
#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; ++i) {
std::cout << "Element " << i << ": " << arr[i] << std::endl;
}
return 0;
}
The for loop provides a concise way to iterate over a range or a collection of elements.
28. friend
============================================
#include <iostream>
class Box {
public:
Box(int l, int w, int h) : length(l), width(w), height(h) {}
private:
int length, width, height;
};
int main() {
Box box(3, 4, 5);
std::cout << "Volume of the box: " << calculateVolume(box) <<
std::endl; // Output: 60
return 0;
}
29. goto
============================================
#include <iostream>
int main() {
int count = 0;
start:
std::cout << "Count: " << count << std::endl;
count++;
if (count < 5) {
goto start; // Jump back to start
}
return 0;
}
While goto can create jumps in control flow, its use is often discouraged in favor of
structured programming constructs for better readability and maintainability.
30. if
============================================
#include <iostream>
#include <unordered_map>
int fibonacci(int n) {
if (fib_cache.find(n) != fib_cache.end()) {
return fib_cache[n];
}
if (n <= 1) {
return n;
} else {
fib_cache[n] = fibonacci(n - 1) + fibonacci(n - 2);
return fib_cache[n];
}
}
int main() {
std::cout << "Fibonacci(10): " << fibonacci(10) << std::endl;
return 0;
}
Here, the if condition checks if the Fibonacci value for a given number has already been
calculated and stored, optimizing the function.
31. inline
Inlining is useful for small functions that are frequently called. Here's a case where it helps
with function templating in class definition:
============================================
template <typename T>
class MathOps {
public:
inline T multiply(T a, T b) {
return a * b;
}
};
int main() {
MathOps<int> math;
std::cout << math.multiply(5, 3) << std::endl; // Output: 15
return 0;
}
This reduces the overhead of frequent function calls in template classes, where speed is
critical.
32. int
============================================
#include <iostream>
#include <vector>
int main() {
int vertices = 5;
std::vector<std::vector<int>> graph(vertices,
std::vector<int>(vertices, 0));
Here, int is used to define the number of vertices and edges in a graph.
33. long
============================================
#include <iostream>
long factorial(long n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
int main() {
long number = 20; // Factorial of large number
std::cout << "Factorial of " << number << " is " << factorial(number)
<< std::endl;
return 0;
}
34. mutable
============================================
#include <iostream>
#include <string>
#include <mutex>
class Logger {
mutable std::mutex mtx;
std::string log;
public:
void log_message(const std::string& message) const {
std::lock_guard<std::mutex> lock(mtx);
log += message + "\n";
}
int main() {
Logger logger;
logger.log_message("Initializing system...");
logger.log_message("System started.");
logger.print_log();
return 0;
}
The mutable keyword allows the mutex to be modified even when log_message is called on
a const object.
35. namespace
============================================
#include <iostream>
namespace Graphics {
void draw() {
std::cout << "Drawing from Graphics namespace" << std::endl;
}
}
namespace Physics {
void draw() {
std::cout << "Drawing from Physics namespace" << std::endl;
}
}
int main() {
Graphics::draw();
Physics::draw();
return 0;
}
Using namespace helps to avoid naming conflicts in larger projects where libraries might
define functions with similar names.
36. new
============================================
#include <iostream>
struct Node {
int value;
Node* left;
Node* right;
Node(int v) : value(v), left(nullptr), right(nullptr) {}
};
int main() {
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(15);
delete root->left;
delete root->right;
delete root;
return 0;
}
37. operator
class Array {
int* data;
int size;
public:
Array(int size) : size(size) {
data = new int[size];
}
~Array() {
delete[] data;
}
};
int main() {
Array arr(10);
arr[0] = 100;
std::cout << arr[0] << std::endl;
return 0;
}
Here, the [] operator is overloaded to allow direct access to the array elements.
38. private
============================================
class BankAccount {
private:
double balance;
public:
BankAccount() : balance(0) {}
Private data members ensure that the balance cannot be directly accessed or modified from
outside the class.
39. protected
============================================
#include <iostream>
class Animal {
protected:
std::string species;
public:
Animal(const std::string& spec) : species(spec) {}
};
void speak() {
std::cout << "I am a " << species << std::endl;
}
};
int main() {
Dog myDog;
myDog.speak();
return 0;
}
Here, the protected member species is accessible to the derived class Dog.
40. public
============================================
#include <iostream>
class Base {
public:
void show() {
std::cout << "Base class" << std::endl;
}
};
int main() {
Derived obj;
obj.show(); // Outputs "Derived class"
obj.Base::show(); // Outputs "Base class"
return 0;
}
The derived class show() method is called, but the Base class method can also be accessed
due to public inheritance.
41. register
Though mostly ignored by modern compilers, register can still hint for small, frequently
used variables:
============================================
void addNumbers() {
register int sum = 0;
for (register int i = 0; i < 1000; ++i) {
sum += i;
}
std::cout << "Sum: " << sum << std::endl;
}
43. return
Using return in a function that handles large computations and returns early based on a
condition:
============================================
#include <iostream>
int expensiveComputation(int n) {
if (n < 0) {
return -1; // Return early for invalid input
}
int result = 0;
for (int i = 0; i < n; ++i) {
result += i * i; // Some complex computation
}
return result;
}
int main() {
std::cout << "Computation result: " << expensiveComputation(5) <<
std::endl;
return 0;
}
Here, the function uses return to handle invalid inputs early, making the code more efficient
and readable.
44. short
Handling short type with bit-level operations:
============================================
#include <iostream>
int main() {
short a = 0b10101010; // 170 in binary
short b = 0b11001100; // 204 in binary
Here, short is used for bitwise operations, showcasing its use in memory-constrained
environments where smaller integer types are preferred.
45. signed
This keyword explicitly specifies that a variable can hold both positive and negative values:
============================================
#include <iostream>
int main() {
signed int a = -42;
signed int b = 1024;
std::cout << "a: " << a << ", b: " << b << std::endl;
return 0;
}
While int is signed by default, explicitly using signed can improve code clarity, particularly
when mixing with unsigned types.
46. sizeof
An advanced use of sizeof to calculate the size of dynamically allocated arrays or struct
padding:
============================================
#include <iostream>
struct MyStruct {
char a;
int b;
double c;
};
int main() {
MyStruct obj;
std::cout << "Size of MyStruct: " << sizeof(MyStruct) << " bytes" <<
std::endl;
sizeof helps in understanding memory layout and calculating storage space for dynamic
memory allocations.
47. static
============================================
#include <iostream>
void counter() {
static int count = 0;
++count;
std::cout << "Count: " << count << std::endl;
}
int main() {
for (int i = 0; i < 5; ++i) {
counter();
}
return 0;
}
Here, static ensures that the count variable retains its value between function calls,
effectively making it a function-level "global."
48. static_cast
============================================
#include <iostream>
class Base {
public:
virtual void show() { std::cout << "Base class" << std::endl; }
};
class Derived : public Base {
public:
void show() override { std::cout << "Derived class" << std::endl; }
};
int main() {
Base* basePtr = new Derived();
Derived* derivedPtr = static_cast<Derived*>(basePtr);
derivedPtr->show(); // Outputs: Derived class
delete basePtr;
return 0;
}
static_cast is used here to convert a base class pointer to a derived class pointer, ensuring
type safety.
49. struct
============================================
#include <iostream>
struct Node {
int data;
Node* next;
};
int main() {
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};
printList(head); // Output: 1 2 3
return 0;
}
struct is commonly used in data structures like linked lists due to its simplicity and default
public access.
50. switch
Advanced control flow with switch using enum types:
============================================
#include <iostream>
int main() {
printColor(Color::Green); // Output: Green
return 0;
}
Here, switch is used with scoped enums (enum class), ensuring type safety.
51. template
============================================
#include <iostream>
template <>
void print<int>(int value) {
std::cout << "Specialized for int: " << value << std::endl;
}
int main() {
print(42); // Specialized for int
print(3.14); // Generic
print("Hello"); // Generic
return 0;
}
template allows code to be reused for different types, with specialization enabling
customization for specific types.
52. this
============================================
#include <iostream>
class Chainable {
int value;
public:
Chainable() : value(0) {}
Chainable& add(int x) {
value += x;
return *this;
}
Chainable& subtract(int x) {
value -= x;
return *this;
}
void print() {
std::cout << "Value: " << value << std::endl;
}
};
int main() {
Chainable obj;
obj.add(10).subtract(3).add(5).print(); // Output: Value: 12
return 0;
}
this allows method chaining, where multiple methods can be called in a sequence on the
same object.
53. throw
============================================
#include <iostream>
int main() {
try {
std::cout << divide(10, 2) << std::endl; // Outputs 5
std::cout << divide(10, 0) << std::endl; // Throws exception
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
Here, throw is used to raise an exception when an error condition occurs (division by zero),
and try-catch blocks are used to handle it.
54. true
============================================
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<bool> flag(true);
void worker() {
while (flag) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Working..." << std::endl;
}
}
int main() {
std::thread t(worker);
std::this_thread::sleep_for(std::chrono::seconds(1));
flag = false;
t.join();
return 0;
}
In this example, true is used with a flag to control a multi-threaded loop that terminates
when the flag is set to false.
55. try
int main() {
try {
riskyOperation(10); // Valid operation
riskyOperation(-5); // Will throw an exception
} catch (const MyException& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
In this example, try is used to catch a custom exception when a risky operation fails.
56. type_info
============================================
#include <iostream>
#include <typeinfo>
class Base {
public:
virtual ~Base() {}
};
int main() {
Base* base = new Derived();
printTypeInfo(base); // Outputs the type of Derived
delete base;
return 0;
}
type_info provides information about the type of an object at runtime, especially useful in
polymorphic scenarios.
57. typedef
============================================
#include <iostream>
#include <vector>
int main() {
PointList points = { {1, 2}, {3, 4}, {5, 6} };
Here, typedef is used to simplify the declaration of a complex type, making the code more
readable.
58. typeid
============================================
#include <iostream>
#include <typeinfo>
class Base {
public:
virtual ~Base() {}
};
int main() {
Base* obj = new Derived();
std::cout << "Type of obj: " << typeid(*obj).name() << std::endl; //
Outputs the type of Derived
delete obj;
return 0;
}
typeid is particularly useful for checking the actual type of an object when working with
polymorphism.
59. typename
============================================
#include <iostream>
#include <vector>
private:
std::vector<T> data;
};
int main() {
MyContainer<int> container;
container.add(10);
std::cout << "First element: " << *container.begin() << std::endl; //
Output: 10
return 0;
}
60. union
============================================
#include <iostream>
union Data {
int intValue;
float floatValue;
char charValue;
};
int main() {
Data data;
data.intValue = 42;
std::cout << "Integer: " << data.intValue << std::endl;
return 0;
}
union allows storing different data types in the same memory location, but only one member
can hold a value at a time.
61. unsigned
============================================
#include <iostream>
int main() {
unsigned int a = 5;
unsigned int b = 10;
return 0;
}
unsigned types are useful when you know that negative values are not needed, thus
providing a larger range for positive values.
62. using
============================================
#include <iostream>
#include <vector>
int main() {
IntVector numbers = {1, 2, 3, 4, 5};
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
The using directive provides an alternative to typedef, making code cleaner and more
expressive.
63. virtual
============================================
#include <iostream>
class Base {
public:
virtual void show() {
std::cout << "Base class" << std::endl;
}
virtual ~Base() {}
};
int main() {
Base* basePtr = new Derived();
basePtr->show(); // Outputs: Derived class
delete basePtr;
return 0;
}
The virtual keyword enables dynamic dispatch, allowing derived class methods to be called
through base class pointers.
64. void
Using void as a return type for functions that do not return a value:
============================================
#include <iostream>
void printMessage() {
std::cout << "This is a message." << std::endl;
}
int main() {
printMessage(); // Calls the function
return 0;
}
void indicates that the function does not return any value, which is common for functions
that perform actions but do not need to send data back