# assert

***

**1. Input Validation:**

```cpp
void validateInput(int input) {
  assert(input >= 0);
}
```

**2. Parameter Checking:**

```cpp
class MyClass {
public:
  MyClass(int value) {
    assert(value > 0);
    // ...
  }
};
```

**3. Memory Allocation:**

```cpp
int* allocateMemory(size_t size) {
  int* ptr = new int[size];
  assert(ptr != nullptr);
  return ptr;
}
```

**4. Object Validation:**

```cpp
class Person {
public:
  Person(const std::string& name) {
    assert(!name.empty());
    // ...
  }
};
```

**5. State Invariants:**

```cpp
class Stack {
private:
  std::vector<int> data;
  int top;
public:
  int pop() {
    assert(!isEmpty());
    // ...
  }

  bool isEmpty() const {
    return top == -1;
  }
};
```

**6. Range Checking:**

```cpp
void printArray(int* arr, int size) {
  assert(arr != nullptr);
  assert(size >= 0);
  // ...
}
```

**7. Index Checking:**

```cpp
std::vector<int> v = {1, 2, 3};
int index = 1;
assert(index >= 0 && index < v.size());
int value = v[index];
```

**8. Resource Release:**

```cpp
void closeFile(File* file) {
  assert(file != nullptr);
  file->close();
}
```

**9. Assertions in Loops:**

```cpp
for (int i = 0; i < 10; i++) {
  assert(i < 10);
  // ...
}
```

**10. Conditional Assertions:**

```cpp
#ifdef DEBUG
  assert(condition);
#endif
```

**11. Testing Input Parameters:**

```cpp
void sum(int a, int b) {
  assert(a >= 0 && b >= 0);
  int result = a + b;
  // ...
}
```

**12. Checking for Null Pointers:**

```cpp
void initializePointer(int* ptr) {
  assert(ptr != nullptr);
  *ptr = 0;
}
```

**13. Enforcing Preconditions:**

```cpp
int divide(int a, int b) {
  assert(b != 0);
  return a / b;
}
```

**14. Checking for Array Bounds:**

```cpp
void printArray(int arr[], int size) {
  assert(arr != nullptr);
  assert(size >= 0);
  for (int i = 0; i < size; i++) {
    printf("%d\n", arr[i]);
  }
}
```

**15. Validating Input Parameters for Functions:**

```cpp
bool isPrime(int n) {
  assert(n >= 2);
  // ...
}
```

**16. Checking for Invalid States:**

```cpp
class MyClass {
public:
  void doSomething() {
    assert(m_isValid);
    // ...
  }
private:
  bool m_isValid;
};
```

**17. Debugging Algorithm Implementations:**

```cpp
int binarySearch(int arr[], int size, int target) {
  assert(arr != nullptr);
  assert(size >= 0);
  assert(isSorted(arr, size));
  // ...
}
```

**18. Ensuring Invariants in Data Structures:**

```cpp
class BinarySearchTree {
public:
  void insert(int value) {
    assert(isBinarySearchTree());
    // ...
  }
private:
  bool isBinarySearchTree() {
    // ...
  }
};
```

**19. Testing Class Member Functions:**

```cpp
class MyClass {
public:
  int getLength() {
    assert(m_data != nullptr);
    return m_length;
  }
private:
  int* m_data;
  int m_length;
};
```

**20. Checking for Invalid Arguments:**

```cpp
void printMessage(std::string message) {
  assert(!message.empty());
  printf("%s\n", message.c_str());
}
```

**21. Asserting Consistency in Multithreaded Code:**

```cpp
std::mutex mtx;
int sharedVariable;

void thread1() {
  mtx.lock();
  sharedVariable++;
  assert(sharedVariable < 100);
  mtx.unlock();
}
```

**22. Ensuring Correctness in File Operations:**

```cpp
std::ifstream file;
file.open("data.txt");
assert(file.is_open());
// ...
```

**23. Checking for Infinite Loops:**

```cpp
int count = 0;
while (true) {
  assert(count < 1000);
  count++;
}
```

**24. Asserting Conditions in Unit Tests:**

```cpp
TEST(MyClass, Method1) {
  MyClass obj;
  int result = obj.method1();
  ASSERT_EQ(result, 5);
}
```

**25. Validating Input in Command Line Applications:**

```cpp
int main(int argc, char* argv[]) {
  assert(argc > 1);
  std::string filename = argv[1];
  // ...
}
```

**26. Detecting Invalid State in Objects:**

```cpp
class MyClass {
public:
  void setProperty(int value) {
    assert(m_state == VALID);
    // ...
  }
private:
  enum State {
    VALID,
    INVALID
  };
  State m_state;
};
```

**27. Asserting Correctness in Data Transformations:**

```cpp
std::vector<int> transformData(std::vector<int>& data) {
  assert(data.size() > 0);
  // ...
}
```

**28. Ensuring Correctness in Exception Handling:**

```cpp
try {
  // Risky code
}
catch (std::exception& e) {
  assert(std::string(e.what()).find("error") != std::string::npos);
}
```

**29. Checking for Invalid Input in Network Operations:**

```cpp
void sendPacket(std::string data) {
  assert(!data.empty());
  // ...
}
```

**30. Validating Input in User Interfaces:**

```cpp
class MyWindow : public QWidget {
public:
  MyWindow() {
    // ...
    connect(m_button, &QPushButton::clicked, this, &MyWindow::validateInput);
  }
private:
  void validateInput() {
    assert(!m_inputField->text().isEmpty());
  }
};
```

**31. Asserting Correctness in Database Operations:**

```cpp
void insertRecord(std::string table, std::string values) {
  assert(!table.empty());
  assert(!values.empty());
  // ...
}
```

**32. Checking for Missing Files in Resource Loading:**

```cpp
void loadTexture(std::string filename) {
  assert(fileExists(filename));
  // ...
}
```

**33. Verifying Correctness of Calculations:**

```cpp
int calculateResult(int a, int b, char op) {
  assert(op == '+' || op == '-' || op == '*');
  // ...
}
```

**34. Detecting Invalid Enum Values:**

```cpp
enum MyEnum {
  ONE,
  TWO,
  THREE
};

void handleEnum(MyEnum value) {
  assert(value >= ONE && value <= THREE);
  // ...
}
```

**35. Ensuring Correctness in String Operations:**

```cpp
void reverseString(std::string& str) {
  assert(!str.empty());
  // ...
}
```

**36. Validating Input Parameters in Templates:**

```cpp
template <typename T>
void sortArray(T arr[], int size) {
  assert(arr != nullptr);
  assert(size >= 0);
  // ...
}
```

**37. Checking for NullPointerExceptions in Java:**

```java
public static void main(String[] args) {
  String name = null;
  assert name != null;
}
```

**38. Verifying Correctness in Graph Algorithms:**

```cpp
void dfs(int node) {
  assert(node >= 0 && node < numNodes);
  // ...
}
```

**39. Detecting Logical Errors in Code:**

```cpp
int main() {
  int x = 10;
  int y = 0;
  int z = x / y; // Will cause runtime error
  assert(y != 0);
}
```

**40. Verifying Correctness in Multithreading:**

```cpp
std::mutex mtx;
std::vector<int> sharedData;

void thread1() {
  mtx.lock();
  sharedData.push_back(1);
  mtx.unlock();
}
```

**41. Validating HTTP Response Codes:**

```cpp
void handleHttpResponse(int code) {
  assert(code >= 200 && code < 600);
  // ...
}
```

**42. Detecting Invalid Arguments in Python:**

```python
def divide(a, b):
  assert b != 0, "Cannot divide by zero"
  return a / b
```

**43. Verifying Correctness in Pandas DataFrame Operations:**

```python
import pandas as pd

df = pd.DataFrame({'a': [1, 2, 3]})
assert df.shape[0] == 3
```

**44. Validating Data in Regression Models:**

```python
import numpy as np

def fit_model(X, y):
  assert X.shape[0] == y.shape[0], "Input data must have same number of rows"
  # ...
```

**45. Detecting Errors in Database Connections:**

```python
import mysql.connector

def connect_to_database():
  try:
    cnx = mysql.connector.connect(host='localhost', user='root', password='pass')
  except Exception as e:
    assert False, "Error connecting to database: " + str(e)
```

**46. Verifying Consistency of Sets:**

```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}

assert set1.symmetric_difference(set2) == {1, 4}
```

**47. Ensuring Correctness in Data Structures:**

```python
class Node:
  def __init__(self, value):
    assert value is not None, "Node value cannot be None"
```

**48. Validating Input in Command Line Arguments:**

```python
import sys

def main():
  assert len(sys.argv) == 2, "Usage: python script.py <argument>"
  # ...
```

**49. Verifying Correctness in Unit Tests (pytest):**

```python
import pytest

def sum(a, b):
  assert a + b == 6

def test_sum():
  sum(2, 4)
```

**50. Detecting Memory Leaks in C++:**

```cpp
#include <gtest/gtest.h>

TEST(LeakDetection, CheckLeak) {
  ASSERT_EQ(0, LeakDetector::getOutstandingLeaks());
  // ... Leaky code here ...
  ASSERT_EQ(0, LeakDetector::getOutstandingLeaks());
}
```
