Number of elements in ArrayType?

Hi!

How can I get the number of elements in ArrayType?

/k

It depends on the type of the ArrayType. ArrayType is the base class of ConstantArrayType, DependentSizedArrayType, IncompleteArrayType, and VariableArrayType.

You have to dyn_cast to whichever the array is. Note that only ConstantArrayType has a constant size (with its function getSize(), or getSizeExpr for the expression itself).

DependentSizedArrayType will show up in a template, if the size itself is a template parameter (you can get THAT with getSizeExpr()).

VariableArrayType represents a VLA (variable length array), so it will also have a getSizeExpr() that isn't calculatable at compile time.

IncompleteArrayType does not have a size.

Assume that you have the desired `VarDecl` `D`:

       const Expr *SizeExpr = nullptr;
        if (D->getType()->isArrayType())
          if (const TypeSourceInfo *TSI = D->getTypeSourceInfo())
            if (const auto ATL = TSI->getTypeLoc().getAs<ArrayTypeLoc>())
              SizeExpr = ATL.getSizeExpr();

I'm having a MemberExpr not a VarDecl. I thought it was thru TypeInfo I
could get the number of elements in the array?

Looks as it can be done like this (arr is ConstantArrayType)

arr->getSize().getZExtValue()

Is my understanding correct?

Erich has pointed out the hierarchy of array types [1], where a
`ConstantArrayType` has such a method `getSize()` to obtain the
concrete size directly. However, most of the time you are able to
obtain the `VariableArrayType`'s size, being a `DeclRefExpr` to a
constant integer. My solution obtains the size expression and let you
decide what you want to do and how generic your solution needs to be.
I have not worked with `DependentSizedArrayType` yet.

[1] https://clang.llvm.org/doxygen/classclang_1_1ArrayType.html