Skip to content

Commit c224275

Browse files
committed
variable length arrays
1 parent 9a8cd76 commit c224275

1 file changed

Lines changed: 31 additions & 1 deletion

File tree

content/posts/cpp-for-cscharp.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,8 @@ Important differences:
693693
- In C# you write ``int[] name``, while in C++ you write ``int name[]``, it differs where you place the brackets.
694694
- In C# arrays are generally on the heap and made with ``new``, in C++ arrays can be both on the stack or heap
695695
- In C# ``int[][]`` is a jagged array while in C++ ``int[][]`` is a multidimensional array.
696+
- In C++ an array can not be copied by value ``int foo[] = bar;``, must use ``memcopy`` instead.
697+
- In C++ an array can not be returned from a function by value, only by pointer.
696698
- In C++ a list is called a vector (yes thats really confusing).
697699

698700
In C# you use arrays like so:
@@ -1559,4 +1561,32 @@ Vec3 v = (Vec3){1.0f, 2.0f, 3.0f};
15591561

15601562
// compound literal for an array
15611563
int* arr = (int[]){1, 2, 3, 4, 5};
1562-
```
1564+
```
1565+
1566+
**Variable Length Arrays**
1567+
1568+
A variable length array is an array whose size is not known at compile time but gets determined at runtime.
1569+
1570+
```c
1571+
// plain c
1572+
1573+
// in both plain c and cpp you can have an array like this
1574+
int arr[16]; // <- size is known at compile time
1575+
1576+
// but in plain c you can also have an array like this (not possible in cpp)
1577+
int n = 16; // <- runtime variable
1578+
int arr[n]; // < size is determined at runtime
1579+
1580+
// you can even use it for runtime sized multi dimensional arrays
1581+
int matrix[rows][cols];
1582+
```
1583+
1584+
**The limitations of a variable length array:**
1585+
- they can only be on the stack, not the heap
1586+
- they can only exist in local scope, not global
1587+
- they can not be returned from a function (like any array)
1588+
- they can not be members of any struct
1589+
- they can not be ``static`` or ``extern`` variables
1590+
- they can not have an initializer at declaration like ``int arr[n] = {1,2,3,4,5};``
1591+
- they can not be used with ``typedef`` to create a wrapper type
1592+

0 commit comments

Comments
 (0)