This commit is contained in:
2025-12-03 16:00:06 +03:30
5 changed files with 536 additions and 132 deletions
@@ -14,18 +14,18 @@
## 📦 Download All Questions and Solutions ## 📦 Download All Questions and Solutions
- **All questions (zip):** [Download all questions](https://drive.google.com/file/d/1SaM7dICduui9NjqiqHTU-5L_AftlvoHE/view?usp=drive_link) - **All questions (zip):** [Download all questions](https://drive.usercontent.google.com/u/0/uc?id=1uGJNRr4f5Iox6hO5GG8Z3mh--h9nvlOW&export=download)
- **All official solutions (zip):** [Download all official solutions](https://drive.google.com/file/d/1V3GwUGKBhvXT5Ab1fDy7Ek27x-1Q4Nny/view?usp=drive_link) - **All official solutions (zip):** [Download all official solutions](https://drive.usercontent.google.com/u/0/uc?id=1-0tuy6QAJTkjfcher1CfEX80D2Hd6wxM&export=download)
--- ---
## 🧾 Official Questions & Solutions ## 🧾 Official Questions & Solutions
| Question # | Question (Download) | Official Solution (Download) | Additional Notes | | Question # | Question (Download) | Official Solution (Download) | Additional Notes |
| ---------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------- | | ---------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------- |
| 01 | [Download PDF](https://drive.google.com/file/d/1mQd1oFr605IYz8SFA0u07_tt8w5ibEIp/view?usp=sharing) | [Download Solution (zip)](https://drive.google.com/file/d/1suqDVN3OtZDS4EnfJInVoM1tal6QWUit/view?usp=drive_link) | | | 01 | [Download PDF](https://drive.usercontent.google.com/u/0/uc?id=1GhdjRDM-sWt3MTpcBrDqkU1yx8FnBzv7&export=download) | [Download Solution](https://drive.usercontent.google.com/u/0/uc?id=1qA6hHF1hxlvQrqkvOS3hWsox8AoRHcQ_&export=download) | |
| 02 | [Download PDF](https://drive.google.com/file/d/1mv7Mp3gxYSK1r-OH5h88ueJMSUCSC-Gc/view?usp=drive_link) | [Download Solution (zip)](https://drive.google.com/file/d/1UUlwNpQvdQU7S_h_azYSAudxsZKi6NtW/view?usp=drive_link) | | | 02 | [Download PDF](https://drive.usercontent.google.com/u/0/uc?id=11lTTfGuvo82-2FsVOq0Jqi-vKblBUo4n&export=download) | [Download Solution](https://drive.usercontent.google.com/u/0/uc?id=17iN4_1VNJoxcmtsN5ImZdhcPDzxKMwQt&export=download) | |
| 03 | [Download PDF](https://drive.google.com/file/d/1FT1YFfGDekytEDnRd2wNThTNRIJ0Gtvx/view?usp=drive_link) | [Download Solution (zip)](https://drive.google.com/file/d/1vtC4GwdEd2Q3YSos9FWzJeYEJy_4gwuu/view?usp=drive_link) | | | 03 | [Download PDF](https://drive.usercontent.google.com/u/0/uc?id=1wpbF9oN0aJFgdfmdPuYtL6XFNKnKhaCb&export=download) | [Download Solution](https://drive.usercontent.google.com/u/0/uc?id=1bsX8YkSJk5dCYtj2zPdEpKN3qz4lcUnz&export=download) | |
| 04 | [Download PDF](https://drive.google.com/file/d/1ql1-JOaNArnH4aHjOvZkmWqYyDFcAKsV/view?usp=drive_link) | [Download Solution (zip)](https://drive.google.com/file/d/17gfm6Ocl1RrA57FLJC4DS2-hn_gvVfFZ/view?usp=drive_link) | | | 04 | [Download PDF](https://drive.usercontent.google.com/u/0/uc?id=1SazPjE6T6tlyMVBS2D7stj96NFaBBuF-&export=download) | [Download Solution ](https://drive.usercontent.google.com/u/0/uc?id=1Adsdk-y5mTTuzoMXB_Yqk_-OxEX2vBdd&export=download) | |
> [!note] Not available yet? > [!note] Not available yet?
> Some solutions will be uploaded after the workshop or assignment deadline. Check back later or ask your TA. > Some solutions will be uploaded after the workshop or assignment deadline. Check back later or ask your TA.
@@ -14,24 +14,26 @@
## 📦 Download All Questions and Solutions ## 📦 Download All Questions and Solutions
- **All questions (zip):** [Download all questions]() - **All questions (zip):** [Download all questions](https://drive.google.com/file/d/1c1CjY-8ZXl9McJwZYQ3dvhItypLoY2rv/view?usp=drive_link)
- **All official solutions (zip):** [Download all official solutions]() - **All official solutions (zip):** [Download all official solutions](https://drive.google.com/file/d/1wENaCV4xPj9UJ9KWAb4lYWHuq4Ncg4Ys/view?usp=drive_link)
--- ---
## 🧾 Official Questions & Solutions ## 🧾 Official Questions & Solutions
| Question # | Question (Download) | Official Solution (Download) | Additional Notes | | Question # | Question (Download) | Official Solution (Download) | Additional Notes |
| ---------- | ------------------- | ---------------------------- | ---------------- | | ---------- | ------------------- | ---------------------------- | ---------------- |
| 01 | [Download PDF]() | [Download Solution (zip)]() | | | 01 | [Download PDF](https://drive.google.com/file/d/19mJ5-wwQtHTeSNCR5gipx0Fk_id6y52i/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1X914229uhoWPjcCHz0mV3L4cQQBgSxq3/view?usp=drive_link) | |
| 02 | [Download PDF]() | [Download Solution (zip)]() | | | 02 | [Download PDF](https://drive.google.com/file/d/1YdSugPfd3nuO-FeTi1IR1gWaThwFnodn/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1PBIw5SAbMhy51Pi0r7Huj1OYtErMiiho/view?usp=drive_link) | |
| 03 | [Download PDF]() | [Download Solution (zip)]() | | | 03 | [Download PDF](https://drive.google.com/file/d/1ZUaHyNn22esmZ3kcEr36HYVLtzQc4ARr/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1a0lVBhT1a3T2Ca0T0VXuj5Un2cohmEzI/view?usp=drive_link) | |
| 04 | [Download PDF]() | [Download Solution (zip)]() | | | 04 | [Download PDF](https://drive.google.com/file/d/1xqWba-bhqve8pNXKAuStU98VxqqY__62/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1TP_I-7fHQZpVIy0i4s6-1lgGvteMIg6-/view?usp=drive_link) | |
| 05 | [Download PDF]() | [Download Solution (zip)]() | | | 05 | [Download PDF](https://drive.google.com/file/d/1WD-9G1MIluzMGPD5glozXnzdHnAPcLJ8/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1U5ohtp-bQNRgJrarEdQ9soxMmYZhabyM/view?usp=drive_link) | |
| 06 | [Download PDF]() | [Download Solution (zip)]() | | | 06 | [Download PDF](https://drive.google.com/file/d/1JyxXKPmoAg81qtr_aCp2EZ_hQjXIeXvg/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/17o_3WsfQ6lQra2T_E1KfLyT-FkRJMqW6/view?usp=drive_link) | |
| 07 | [Download PDF]() | [Download Solution (zip)]() | | | 07 | [Download PDF](https://drive.google.com/file/d/1xn7sQvQo4fNWpdRvxIJ1d0dEcNcUv4mM/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1TCOxjhLDJxYuKoeIbqwJcOTbf_yvXQe-/view?usp=drive_link) | |
| 08 | [Download PDF]() | [Download Solution (zip)]() | | | 08 | [Download PDF](https://drive.google.com/file/d/18TnSu2aYhJ0yH65Elfc1vtMxJrNbiLcc/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1U7Ba5wt9J_ZxYxE-HqX0N1pEsotBmPGC/view?usp=drive_link) | |
| 09 | [Download PDF]() | [Download Solution (zip)]() | | | 09 | [Download PDF](https://drive.google.com/file/d/14sMHbklVGObk7sCpMitUC2U1h7PHdiGy/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/15Fafu44WVXGp0aB2RG8LFBE8B8lPg-ze/view?usp=drive_link) | |
| 10 | [Download PDF]() | [Download Solution (zip)]() | | | 10 | [Download PDF](https://drive.google.com/file/d/1gxDU5ttREfrdOLDBTxBCzqhFsRrjuosK/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/121Z0G2NkxW2L4iUEaRL5R9G_pdS3CfBV/view?usp=drive_link) | |
| 11 | [Download PDF](https://drive.google.com/file/d/1XhjrKZ88FFADWi_RbmDmdigu3ESo19k1/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1e-9XiH7N8E8iJktnBhtiYrbbYUE8Y_h8/view?usp=drive_link) | |
| 12 | [Download PDF](https://drive.google.com/file/d/1-EA5FpLIyuDDYrwlw0LfJNMC1ZHRQykd/view?usp=drive_link) | [Download Solution (cpp)](https://drive.google.com/file/d/1sdjbw89d1vd3kzuQu-4qhPhjccirLTf4/view?usp=drive_link) | |
> [!note] Not available yet? > [!note] Not available yet?
> Some solutions will be uploaded after the workshop or assignment deadline. Check back later or ask your TA. > Some solutions will be uploaded after the workshop or assignment deadline. Check back later or ask your TA.
+83 -101
View File
@@ -1,133 +1,114 @@
# 🧭 Topic: Function Basics # 🧭 Topic: Function Basics
> [!info] **Quick Overview :**
> [!info] Quick Overview
> >
> This topic introduces functions in C++, why we use them, how they are
> defined and called, how parameters and return values work, and how to
> write clean, professional function-based code.
--- ---
## 📌 Covered in This Topic ## 📌 Covered in This Topic
**Introduction to Functions** ### **Introduction to Functions**
- What functions are - What functions are (self-contained blocks of code)
- Key goals: modularity, reuse, readability, debugging - Key goals:
- Real-world analogy: “tasks” or “machines” that take input and produce output - Modularity
- Reusability (Write once, use everywhere)
- Readability
- Debugging & error isolation
- Real-world analogy: a “machine” that takes input and produces output
**Why We Need Functions** ### **Why We Need Functions**
- Code reuse - Eliminating repetition (D.R.Y. — Dont Repeat Yourself)
- Reducing complexity
- Avoiding repetition
- Breaking problems into sub-problems - Breaking problems into sub-problems
- Making programs testable - Reducing complexity
- Collaboration benefits: multiple people working on different functions - Abstraction (main doesnt care *how*, only *what*)
- Professional collaboration benefits
**Predefined Library Functions** ### **User-Defined Functions**
- Overview of `<cmath>`, `<iomanip>`, helpers - Anatomy of a function:
- Calling library functions (syntax, examples) - Return type
- Function name
- Parameters
- Body
- Function lifecycle:
- Declaration (prototype)
- Definition
- Calling
- Declaration vs. Definition
- Function prototypes and their purpose
**User-Defined Functions** ### **Return Types**
- Components of a user-defined function - Allowed return types
- **Declaration** vs. **Definition** vs. **Call** - Limitation: a function returns only **one value**
- Variables inside functions (local variables & scope) - `void` functions:
- Global variables — why to avoid them - Definition and use cases
- Lifetime and visibility of variables - Using `return;` as an “exit door”
**Parameters, Arguments & Terminology** ### **Parameters & Arguments**
- Parameter vs. Argument (definition, examples) - Parameter vs. argument (placeholder vs. actual data)
- Types of parameters: input, output, in-out - Order and clarity of parameters
- Naming conventions for parameters - Parameter names optional in prototypes
- Why parameter order and clarity matter - Scope and lifetime of parameters
- Common student mistakes (e.g., confusing scope)
**Return Types** ### **Scope & Lifetime**
- `void` vs. non-void - Local variables
- Returning multiple values → reference parameters - Global variables:
- Return type limitations (only one return value) - What they are
- Allowed data types - Why to avoid them
- When to use `return;` in void functions - Static local variables
- Early returns and readability. (Guard Clause) - Variable shadowing
- Priority of scopes
**Function Prototypes** ### **Default Arguments**
- What prototypes do - Syntax of default parameters
- Why prototypes are needed in C++ - Rules:
- Where to place prototypes (before `main` or in headers) - Must be placed on the **right**
- Typical student errors (e.g., mismatched signatures) - Evaluated at **compile time**
- Correct vs. incorrect usage
- Common ambiguity problems
**Default Arguments** ### **Parameter Passing Methods**
- Syntax for default values
- Rules (right-to-left, only in declaration)
- Good vs. bad use cases
- Common pitfalls
**Parameter Passing Methods**
- **Pass by value** - **Pass by value**
- Cheap for ints, bools, chars - Copy is made
- Safe, makes a copy - Original variable unchanged
- Best for small data types
- **Pass by reference (`&`)** - **Pass by reference (`&`)**
- Used for modifying caller variables - Works on original variable
- Used for performance - Used for modification or performance
- **When to choose which method** - When and why to choose each method
- Memory model overview (stack frame, copies)
### **Function Overloading**
- Definition of overloading
- Valid overloading rules
- Return type alone does NOT overload
- Overload resolution basics
- Numeric literal suffixes and their effect
- Overloading vs. default arguments (ambiguity)
**Function Overloading** ### **Clean Code & Best Practices**
- What overloading is - Syntax and formatting
- Rules for valid overloading - Function placement & structure
- Overloading vs. default args and ambiguity - Meaningful naming (verbs for functions)
- Examples: `abs`, `sort`, etc. - SRP (Single Responsibility Principle)
- Common pitfalls (type conversion confusion) - Function length and complexity
- Refactoring deeply nested logic
**Clean Code & Best Practices**
**Syntax**
- Consistent formatting
- Clear parameter naming
- Avoid deeply nested logic inside functions
**Naming**
- Verbs for functions (`calculateTotal`, `isValid`)
- Avoid generic names (`func1`, `doStuff`)
- Self-documenting naming
**SRP (Single Responsibility Principle)**
- One function should do one thing
- How complex is “too complex”?
- When to break a function into smaller pieces
**Function Length & Complexity**
- Cyclomatic complexity
- Indicators that a function needs refactoring
- How to make logic testable
**Scope, Lifetime & Static Functions**
- Local vs. global variables
- Shadowing
- `static` local variables
- When to use function-level statics
- Danger of relying on state
**Common Student Mistakes**
- Defining a function inside another function
- Forgetting to return a value
- Mismatched declaration and definition
- Depending on global variables instead of parameters
- (Optional) Passing large objects by value
--- ---
## 📑 Slides & Materials ## 📑 Slides & Materials
- 👨‍🏫 [Professor Slides (PDF)](01-topics/04-function-1/4-ProfessorSlides.md) - 👨‍🏫 [Professor Slides (PDF)](4-ProfessorSlides.md)
- 🧑‍🏫 [TA Workshop Slides (PDF)](01-topics/04-function-1/5-TASlides.md) - 🧑‍🏫 [TA Workshop Slides (PDF)](5-TASlides.md)
--- ---
## 🛠️ Workshop & Assignments ## 🛠️ Workshop & Assignments
- 💬 [Workshop Questions](01-topics/04-function-1/2-Assignment.md) - 💬 [Workshop Questions](1-Workshop.md)
- 🧮 [Assignments](01-topics/04-function-1/2-Assignment.md) - 🧮 [Assignments](2-Assignment.md)
- ❓ [Q&A and Common Issues]() - ❓ [Q&A and Common Issues]()
--- ---
## 🌐 Additional Resources ## 🌐 Additional Resources
- C++ Reference (cplusplus.com)
- [C++ Reference](https://cplusplus.com/reference/)
--- ---
## ⏩ Navigation ## ⏩ Navigation
@@ -136,6 +117,7 @@
- ➡️ [Next Topic: Arrays](../05-arrays/0-Overview.md) - ➡️ [Next Topic: Arrays](../05-arrays/0-Overview.md)
--- ---
> [!tip] Tip > [!tip] **Tip :**
>
> If something doesnt make sense — **dont stay stuck alone**. Ask the TA to clarify it right away. Often, a quick question can save you a lot of time and frustration. Remember: if youre confused, chances are others are too. > If something doesnt make sense — **dont stay stuck alone**. Ask the TA to clarify it right away. Often, a quick question can save you a lot of time and frustration. Remember: if youre confused, chances are others are too.
@@ -14,18 +14,17 @@
## 📦 Download All Questions and Solutions ## 📦 Download All Questions and Solutions
- **All questions (zip):** [Download all questions]() - **All questions (zip):** [Download all questions](https://drive.usercontent.google.com/u/0/uc?id=19EIICYkB7sUmsEVB6da5eZ5MQ7WTuP88&export=download)
- **All official solutions (zip):** [Download all official solutions]() - **All official solutions (zip):** [Download all official solutions](https://drive.usercontent.google.com/u/0/uc?id=1j0gtsHGPOcpH8GOVAyvxFqecCze1SQH0&export=download)
--- ---
## 🧾 Official Questions & Solutions ## 🧾 Official Questions & Solutions
| Question # | Question (Download) | Official Solution (Download) | Additional Notes | | Question # | Question (Download) | Official Solution (Download) | Additional Notes |
| ---------- | ------------------- | ---------------------------- | ---------------- | | ---------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------- |
| 01 | [Download PDF]() | [Download Solution (zip)]() | | | 01 | [Download PDF](https://drive.usercontent.google.com/u/0/uc?id=1LZysw18yVMxIeSfI5myQ-PJEtHD5_Qgl&export=download) | [Download Solution (cpp)](https://drive.usercontent.google.com/u/0/uc?id=1piw1JTjDYyrfhyDaFOlzbwsyp0exbMws&export=download) | |
| 02 | [Download PDF]() | [Download Solution (zip)]() | | | 02 | [Download PDF](https://drive.usercontent.google.com/u/0/uc?id=1_Qvwn_c2AUgAEYWYLs2D8rwDgzklFr2-&export=download) | [Download Solution (cpp)](https://drive.usercontent.google.com/u/0/uc?id=1njLCfQOu7Wg5JOgigoLM9D8ApACNRleT&export=download) | |
| 03 | [Download PDF]() | [Download Solution (zip)]() | | | 03 | [Download PDF](https://drive.usercontent.google.com/u/0/uc?id=1bUqIBdveAywXfEIxdAMHQdvzrf2qS2H-&export=download) | [Download Solution (cpp)](https://drive.usercontent.google.com/u/0/uc?id=1Ig4BJdoivI__8_1Aj2uZm9-KRWh0zT-1&export=download) | |
| 04 | [Download PDF]() | [Download Solution (zip)]() | |
> [!note] Not available yet? > [!note] Not available yet?
> Some solutions will be uploaded after the workshop or assignment deadline. Check back later or ask your TA. > Some solutions will be uploaded after the workshop or assignment deadline. Check back later or ask your TA.
@@ -38,9 +37,9 @@
> - Revisit the lecture notes and workshop slides. > - Revisit the lecture notes and workshop slides.
> - Ask your TA — thats what were here for. > - Ask your TA — thats what were here for.
- [Topic Q&A](01-topics/02-basics-and-data-types/3-Q&A.md) - [Topic Q&A](3-Q&A.md)
- [Professor Slides](01-topics/02-basics-and-data-types/4-ProfessorSlides.md) - [Professor Slides](4-ProfessorSlides.md)
- [TA Slides](01-topics/02-basics-and-data-types/5-TASlides.md) - [TA Slides](5-TASlides.md)
--- ---
## ⚖️ Licensing & Usage ## ⚖️ Licensing & Usage
+421
View File
@@ -0,0 +1,421 @@
## ❓ Question 1
> Question: _“Where are Variable Length Arrays (arrays sized using a runtime variable) allowed in C++ and where are they not?”_
> [!info] **Answer**
> Variable Length Arrays (**VLAs**) are **not allowed** in standard C++.
> C++ requires the size of a built-in array to be a **constant expression** known at compile time.
-**Not acceptable in standard C++** (C++11/14/17/20/23/…):
```cpp
int n = 5;
int arr[n]; // Not valid C++
```
- ✔️ **Acceptable in standard C** (since C99): C allows VLAs.
- ✔️ **Allowed in GCC as an extension**, but **not portable** and not standard.
Reference:
- GCC documentation: [https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html](https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html)
- C++ restriction explanation: [https://www.geeksforgeeks.org/why-variable-length-array-were-removed-in-cpp/](https://www.geeksforgeeks.org/why-variable-length-array-were-removed-in-cpp/)
---
## ❓ Question 2
> Question: _“Is it valid to use a Variable Length Array when compiling with GCC? In which situations is it not valid?”_
> [!info] **Answer**
> GCC **does allow** VLAs in C++ mode, but **only as a non-standard compiler extension**.
✔️ **OK in GCC when:**
- Used inside functions (automatic storage):
```cpp
int n = 10;
int arr[n]; // GCC accepts, but non-standard
```
❌ **Not OK when:**
- Writing portable or standards-compliant C++
- Using MSVC, Clang with strict mode, or compilers that reject VLAs
- Using strict flags:
- `-std=c++20 -pedantic`
- `-Wvla`
- `-Werror`
GCC reference:
[https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html](https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html)
---
## ❓ Question 3
> Question: _“Why are Variable Length Arrays considered unacceptable or non-standard in C++?”_
> [!info] **Answer**
> VLAs are rejected by the C++ standard for several reasons:
1. **Compile-time determinism**
C++ requires array sizes to be known at compile time for built-in arrays.
2. **Portability issues**
Many compilers (MSVC, strict Clang modes) do not support VLAs at all.
3. **Safety considerations**
Runtime-sized stack arrays risk unpredictable stack usage and stack overflow.
4. **C++ philosophy**
C++ encourages using **RAII containers** (`std::vector`, `std::array`) instead of raw arrays with runtime sizes.
Reference:
[https://www.geeksforgeeks.org/why-variable-length-array-were-removed-in-cpp/](https://www.geeksforgeeks.org/why-variable-length-array-were-removed-in-cpp/)
---
## ❓ Question 4
> Question: _“Can `const` or `constexpr` be used to provide a size for arrays in C++ when the goal is to avoid Variable Length Arrays?”_
> [!info] **Answer**
> Yes — **but only if the value is a compile-time constant expression**.
✔️ Allowed:
```cpp
constexpr int N = 10;
int arr[N]; // Valid C++
```
⚠️ Not allowed:
```cpp
int n = get_input();
const int x = n;
int arr[x]; // Still NOT valid — not a constant expression
```
Summary:
- `constexpr` → always compile-time constant → valid for array sizes
- `const` → **not enough** unless initialized with a compile-time constant
- For real runtime sizes, use `std::vector`.
Reference:
[https://en.cppreference.com/w/cpp/language/array](https://en.cppreference.com/w/cpp/language/array)
## ❓ Question
> Question: _“How are arrays passed to functions in C++? Is it allowed?”_
> [!info] **Answer**
> Yes, it is allowed.
> In C++, when you pass a built-in array to a function, the array **decays into a pointer** to its first element.
> Example:
```cpp
void foo(int arr[]) { } // arr becomes int*
void foo(int* arr) { } // same thing
```
So even though an array looks like it's being passed, **the function receives only a pointer**, not the entire array.
Reference: [https://en.cppreference.com/w/cpp/language/array](https://en.cppreference.com/w/cpp/language/array)
---
## ❓ Question 2
> Question: _“Are arrays passed by reference or by value?”_
> [!info] **Answer**
> A raw array parameter is **never** passed by value.
> The array **decays** to a pointer → this behaves like **pass-by-pointer**, not value.
- ❌ Not pass-by-value (copying an entire array is not what happens)
- ✔️ Effectively pass-by-reference (because the pointer can modify the original array)
If you _do_ want pass-by-value semantics, you must use something like:
```cpp
void foo(std::array<int, 5> arr); // Copies the entire array
```
Reference: [https://en.cppreference.com/w/cpp/language/array](https://en.cppreference.com/w/cpp/language/array)
---
## ❓ Question 3
> Question: _“Can you control this behavior? Can you pass arrays by value or by reference explicitly?”_
> [!info] **Answer**
> Yes — but **only using references or std::array**.
✔️ **Pass entire array by reference** (preserves size):
```cpp
void foo(int (&arr)[5]); // Reference to array of 5 ints
```
✔️ **Pass entire array by value** (copies the whole array):
```cpp
void foo(std::array<int,5> arr); // Copy
```
✔️ **Pass entire array by reference (modern way)**:
```cpp
void foo(const std::array<int,5>& arr);
```
❌ You **cannot** pass a built-in array by value directly.
The syntax does not exist in C++.
Reference: [https://en.cppreference.com/w/cpp/language/references](https://en.cppreference.com/w/cpp/language/references)
---
## ❓ Question 4
> Question: _“Should you specify the size of arrays when passing them? For 1D, 2D, 3D, etc.?”_
> [!info] **Answer**
> It depends on the declaration style.
### ⭐ 1D arrays
You do **not** specify the size:
```cpp
void foo(int arr[]); // OK
void foo(int* arr); // Same
```
### ⭐ Multi-dimensional (2D, 3D, …) arrays
All **inner dimensions must be known**:
```cpp
void foo(int arr[][5]); // OK
void foo(int arr[3][5]); // OK
void foo(int arr[][5][10]); // Higher dimensions OK
```
But the **first dimension** may be left unspecified because it becomes a pointer:
```
arr → pointer to an array of 5 ints
```
Reference: [https://en.cppreference.com/w/cpp/language/array](https://en.cppreference.com/w/cpp/language/array)
---
## ❓ Question 5
> Question: _“Can you use variables as sizes in function parameters? In standard C++ and GCC?”_
> [!info] **Answer**
### ✔️ Standard C++
- **NOT allowed**:
Inner dimensions must be compile-time constants.
```cpp
void foo(int arr[][n]); // ❌ Not standard C++
```
### ✔️ GCC (as extension)
- GCC allows **Variable Length Arrays (VLA)** in function parameters.
```cpp
void foo(int n, int arr[][n]); // ✔️ GCC extension
```
But this is **non-portable** and not valid standard C++.
References:
- Standard rule: [https://en.cppreference.com/w/cpp/language/array](https://en.cppreference.com/w/cpp/language/array)
- GCC VLA extension: [https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html](https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html)
---
## ❓ Question 6
> Question: _“What are the different notations for passing arrays to functions?”_
> [!info] **Answer**
> C++ supports several styles:
### 1️⃣ Pointer style
```cpp
void foo(int* arr);
```
### 2️⃣ Array style (decays to pointer)
```cpp
void foo(int arr[]);
void foo(int arr[10]); // Size ignored by compiler
```
### 3️⃣ Multi-dimensional
```cpp
void foo(int arr[][5]);
```
### 4️⃣ Reference to array (preserves actual size)
```cpp
void foo(int (&arr)[10]);
```
### 5️⃣ Using std::array (recommended for fixed sizes)
```cpp
void foo(std::array<int,10>& arr);
```
### 6️⃣ Using std::vector (recommended for dynamic sizes)
```cpp
void foo(std::vector<int>& arr);
```
Reference: [https://en.cppreference.com/w/cpp/container](https://en.cppreference.com/w/cpp/container)
## ❓ Question: Can you somehow preserve an arrays size and use it in functions?
> **Answer**
> Yes — but only if you pass the array in a way that preserves its compile-time size. By default, when you pass a built-in C-style array to a function, it “decays” into a pointer (so size information is lost). ([GeeksforGeeks](https://www.geeksforgeeks.org/cpp/what-is-array-decay-in-c-how-can-it-be-prevented/?utm_source=chatgpt.com "What is Array Decay in C++? How can it be prevented? - GeeksforGeeks"))
If you want to preserve the size, you can pass by reference to an array. Example:
```cpp
void func(int (&arr)[10]) {
// Here, sizeof(arr)/sizeof(arr[0]) works: size = 10.
}
```
Because `arr` is a reference to an array of 10 ints, the function knows the arrays size at compile time. ([GeeksforGeeks](https://www.geeksforgeeks.org/cpp/pass-array-to-functions-in-cpp/?utm_source=chatgpt.com "Pass Array to Functions in C++ - GeeksforGeeks"))
If you need a function that works for arrays of _any_ compile-time-known size, you can use a template:
```cpp
template <size_t N>
void func(int (&arr)[N]) {
// N is deduced; you can use it inside the function
}
```
This way the function “remembers” the array size. This pattern avoids the “decay to pointer” problem. ([CodeArchPedia.com](https://openillumi.com/en/en-cpp-c-array-decay-type-size-basics/?utm_source=chatgpt.com "C++ Array Decay: Types, Sizes, and Fixing Pointer Conversion Bugs - CodeArchPedia.com"))
Alternatively, many modern C++ codebases avoid raw arrays and instead use container types (e.g. `std::array`, `std::vector`) which carry size information or allow querying their size. ([xeverous.github.io](https://xeverous.github.io/cpp/tutorials/beginner/08_arrays/03_std_array/?utm_source=chatgpt.com "modern C++ by Xeverous - 03 - std::array"))
---
## ❓ Question: How to initialize an array to all zeros? — in 1D, 2D, 3D, etc.
> **Answer**
- For a 1D built-in array in C++, you can zero-initialize like:
```cpp
int arr[5] = {0}; // all 5 elements become 0
```
([GitLab](https://fintechpython.pages.oit.duke.edu/jupyternotebooks/3-CPlusCPlus/14-Built-InArrays/answers/rq-14-answers.html?utm_source=chatgpt.com "CPlusPlus / Built-In Arrays — Programming for Financial Technology"))
- For multi-dimensional (2D, 3D, ...) built-in arrays, you can do nested brace initialization (or rely on partial zero initialization). For example:
```cpp
int mat[3][4] = {0}; // all elements become 0
```
Or for 3D:
```cpp
int cube[2][3][4] = {0};
```
The `{0}` initializes the first element to zero, and all other elements are zero-initialized by default (aggregate initialization rules). ([GitLab](https://fintechpython.pages.oit.duke.edu/jupyternotebooks/3-CPlusCPlus/14-Built-InArrays/answers/rq-14-answers.html?utm_source=chatgpt.com "CPlusPlus / Built-In Arrays — Programming for Financial Technology"))
- Similarly, if you use `std::array`, you can zero-initialize:
```cpp
std::array<int,5> arr = {0};
```
All members will be zero-initialized. ([magodo's blog](https://magodo.github.io/array-string-pointer-reference/?utm_source=chatgpt.com "C++ Array, String, Pointer and Reference"))
So yes — you _can_ initialize multi-dimensional arrays (1D, 2D, 3D, etc.) to zero with a simple initializer (or nested braces).
---
## ❓ Question: Why is there no compile-time error when you access out-of-bounds in a built-in array (i.e. “out of index”)?
> **Answer**
> Because built-in (C-style) arrays in C++ do **not** perform any bounds checking. The language simply allows `arr[i]` for any `i`, and does not verify at runtime whether `i` is valid. Accessing outside the allocated bounds is undefined behavior. ([GitLab](https://fintechpython.pages.oit.duke.edu/jupyternotebooks/3-CPlusCPlus/14-Built-InArrays/answers/rq-14-answers.html?utm_source=chatgpt.com "CPlusPlus / Built-In Arrays — Programming for Financial Technology"))
That means the compiler does not generate an error or warning (in general) if you index beyond the arrays size — it's up to the programmer to ensure correctness. This is a known risk of raw arrays. ([Stack Overflow](https://stackoverflow.com/questions/33319739/why-arent-built-in-arrays-safe?utm_source=chatgpt.com "c++ - Why aren't built-in arrays safe? - Stack Overflow"))
Because of this inherent unsafety (lack of bounds checking, size information lost when passing arrays, no easy way to return raw arrays, etc.), many C++ developers prefer safer alternatives (see below). ([Stack Overflow](https://stackoverflow.com/questions/33319739/why-arent-built-in-arrays-safe?utm_source=chatgpt.com "c++ - Why aren't built-in arrays safe? - Stack Overflow"))
---
## ❓ Question: What is the “standard array” (i.e. `std::array`)? What are the differences between `std::array` and built-in arrays? When is it best to use it?
> **Answer**
> `std::array<T, N>` is a template class in C++ standard library representing a fixed-size array of `N` elements of type `T`. It behaves like a thin wrapper over a built-in array, but with advantages. ([xeverous.github.io](https://xeverous.github.io/cpp/tutorials/beginner/08_arrays/03_std_array/?utm_source=chatgpt.com "modern C++ by Xeverous - 03 - std::array"))
**Differences / Advantages compared to built-in arrays:**
- **No “decay to pointer” when passed to functions**: `std::array` keeps size information. If you pass `std::array<int,5>` to a function by value or by reference, the size is known and preserved. ([xeverous.github.io](https://xeverous.github.io/cpp/tutorials/beginner/08_arrays/03_std_array/?utm_source=chatgpt.com "modern C++ by Xeverous - 03 - std::array"))
- **Supports assignment, copy, move semantics**: Unlike built-in arrays (which are not assignable or copyable as a whole), `std::array` behaves like a regular object. ([Stack Overflow](https://stackoverflow.com/questions/33319739/why-arent-built-in-arrays-safe?utm_source=chatgpt.com "c++ - Why aren't built-in arrays safe? - Stack Overflow"))
- **Has member functions & safer access**: For example, `.at()` performs bounds checking (throws exception on invalid index), while operator `[]` still gives raw access (no bounds check) — unlike built-in arrays where you only get `[]`. ([magodo's blog](https://magodo.github.io/array-string-pointer-reference/?utm_source=chatgpt.com "C++ Array, String, Pointer and Reference"))
- **Interoperability with standard library algorithms**: `std::array` supports iterators, `std::begin()`, `std::end()`, which makes it easier to integrate with STL algorithms. ([xeverous.github.io](https://xeverous.github.io/cpp/tutorials/beginner/08_arrays/03_std_array/?utm_source=chatgpt.com "modern C++ by Xeverous - 03 - std::array"))
**When is `std::array` best to use:**
- When the array size is known at compile time and fixed.
- When you want safer semantics — e.g. ability to copy/assign arrays, pass around by value or reference, avoid the “array decay” problems, and optionally get bounds-checked access via `.at()`.
- When you want to use standard library features (iterators, algorithms) with array data.
For dynamic or runtime-determined sizes (or if size can change), other types like `std::vector`, or (since C++20) `std::span` or dynamic containers are more appropriate. ([xeverous.github.io](https://xeverous.github.io/cpp/tutorials/beginner/08_arrays/03_std_array/?utm_source=chatgpt.com "modern C++ by Xeverous - 03 - std::array"))
---
## What is string in c++? object? class?
## Are strings passed by ref ?
## Are strnigs objects that are in stack? in heap?
## Do strings use arrays in themselves?
## Are strings immutable? are they not?