We often need to know the array dimensions that were previously defined, or to iterate over them, or something else. This is especially true when we show initialization of an array without specifying its dimensions:
int is[]={1,2,3};
Readers with the C language development experience may often use the following methods to implement:
int dimension=sizeof(is)/sizeof(is[0])
This works very well in most cases. Just knocking on the keyboard a bit more times. So, the following macro appears:
#define DIM(a)(sizeof(a)/sizeof(a[0]))
It's much more convenient now. But it's still not perfect. Consider the following:
Macro parameter passes in a custom object with the operator[] operator overloaded
Macro parameters pass in a pointer
Let's look at the first case first. When you pass in an object that has overloaded the operator[] operation (you might say, "Wait, I'll never do that.") "But who will vouch for you?" , the compiler will not give you an error, or even a warning will not be given. You don't believe me? Copy the following code fragment to your IDE and try it out.
1.std::vector<int> VI;
2.cout << DIM (vi) << Endl;
"Damn it, I'm going to replace my fucking compiler!" "Don't worry, as far as I know, there is no manufacturer's compiler to give errors or warnings, and most importantly, the compiler has no responsibility at all."
Before we solve this problem, let's insert a little bit of knowledge about C + + arrays and pointers.
In many cases, arrays in C + + can be degraded to pointers. Here is an example:
1.int is[] = {1, 2, 3};
2.int *pi = is;
There are two ways we can access an array: One is called subscript access, and the other is called an offset access. For example, to get the second element of the array is, you can use is[1] and * (is + 1) respectively, in two ways equivalent. In fact, pointers also have the same characteristics, i.e. pi[1] or * (pi + 1) is also the second element. More interestingly, built-in (build-in) subscript access in C + + can also be written backwards, i.e. is[1] and 1[is] equivalent. Surprise me. It is emphasized that this feature is not available only if the built-in subscript access is correct, in other words, the type of the operator[operator is customized and overloaded. The second element of vector can be obtained by vi[1], and the compiler complains when you write code such as 1[vi.
Well, back to our problem, we can use the C + + features mentioned above to solve. Modify the definition of the Dim macro to:
1. #define DIM (a) (sizeof (a)/sizeof (0[a]))
The first question has been satisfactorily resolved.