Behavior of sizeof on variable length arrays (C only)

前端 未结 2 763
猫巷女王i
猫巷女王i 2020-11-27 07:39

My question is how exactly sizeof() behaves when passed argument is a dynamic array variable length array.

Let\'s consider an example:<

相关标签:
2条回答
  • 2020-11-27 08:06

    My question is how exactly sizeof() behaves when passed argument is a dynamic array.

    1. Well, you rather meant a "variable-length array" (VLA).

    2. It behaves almost exactly the same: it returns the size of the array in bytes.

    sizeof() 'behaves like' a function and not as an operator.

    Nah, it never was a function. The only thing that changes is that if used on VLAs, this operator doesn't yield a compile-time constant, otherwise it does.

    0 讨论(0)
  • 2020-11-27 08:22

    It still behaves as an operator. Cast is also operator and also evaluates it's argument and so does * or & . Being an operator is a syntactic category. That does not change.

    The important distinction is that it behaves as expression while in other cases it behaves as constant.


    Update: I commented below that I don't see why the evaluation makes difference, but now I realized there are two ways you can write sizeof with variable length array. Either you can pass variable declared as variable lenght array:

    int a[x];
    sizeof(a)
    

    in which case evaluating a indeed makes no difference. But you can also use a type as the argument, which would be

    sizeof(int[x])
    

    and in this case the result is x * sizeof(int) and x must be evaluated. Which I suppose is why the specification mentions it.

    0 讨论(0)
提交回复
热议问题