-8

Regarding c variables, I want to know what the x does in:

int var[x]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Lior Dahan
  • 682
  • 2
  • 7
  • 19

2 Answers2

3

This is a declaration of a Variable Length Array (VLA).

The value of expression x (most likely, a variable) is treated as the number of array elements. It must have a positive value at the time the expression is evaluated, otherwise the declaration of the VLA produces undefined behavior.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • AFAIK the variable length array was in C99 standard, but made optional in C11. So the VLA must have seemed like the best thing ever, but for reasons I have not followed fell from favour. Perhaps MS was wise never to have implemented VLA (tongue in cheek). – Weather Vane Feb 08 '17 at 19:36
  • @WeatherVane I agree, VLAs introduce more problems than they solve, because you never know if the declaration is going to crash for `x` being too large for the stack. – Sergey Kalinichenko Feb 08 '17 at 19:38
  • _This is a declaration of a Variable Length Array (VLA)._ Not in this case: `enum values{n, x, y, z};` :) – David Ranieri Feb 08 '17 at 19:47
  • @KeineLust Absent OP's explanation, it's impossible to know. Given that OP's asking, it's unlikely that `x` is constant, because declarations with constants are a lot more common. – Sergey Kalinichenko Feb 08 '17 at 19:49
  • _because you never know if the declaration is going to crash for x being too large for the stack._, good point, what about `int *a[n]; a = malloc(sizeof(*a) * 1000000);`, where `n` is `4`, this will not overflow the stack because `a` is just an array of 4 pointers, even if we reserve a lot of space in the next operation, isn't it? – David Ranieri Feb 08 '17 at 19:55
  • @KeineLust Even simpler - `int *var = malloc(sizeof(*var)*x)`. The only downside is having to call `free`, but that's not as scary as a possibility to overflow the stack. – Sergey Kalinichenko Feb 08 '17 at 20:00
  • @dasblinkenlight, I'm not making myself clear. This will overflow the stack: `int n = 100000000; int a[4][n];` but this not: `int n = 4; int (*a)[n]; a = malloc(sizeof(*a) * 1000000);`, is my assumption correct? – David Ranieri Feb 08 '17 at 20:10
  • 1
    @KeineLust `int *a[n]` is still a large VLA. If you want an array of Nx4, use `int (*a)[4] = malloc(n*sizeof(*a));` with parentheses around `*a`. – Sergey Kalinichenko Feb 08 '17 at 20:23
0

The int defines the type of the variable, the [] defines the variable as an array, the number in the [] says the number of elements in the array. Int var[4] sets var as an array of 4 ints So, after that, var[0] is the first element, var[1] the second and var[3] the last one (index starts in 0 as you can see)

PRDeving
  • 679
  • 3
  • 11