Home c++ Determination of the number of elements in the array

Determination of the number of elements in the array

Author

Date

Category

Now I define the number of elements in a static array using the following expression:

sizeof (array) / Sizeof (Array [0])

I heard that there is a standard macro for this action, tell me how it is called or maybe there is a simpler way?


Answer 1, Authority 100%

template & lt; TypeName T, Size_t N & GT;
INLINE SIZE_T ARRAYSIZE (Const T (& amp; arr) [n])
{
  RETURN N;
}

Compared to the minuses mentioned by the macro, I personally do not see. Any compiler This challenge will simply start the constant.

Are there any advantages? I think yes. Macros – & NBSP; This thing is so rather muddy. They are very easy to make a mistake (see comments to the previous answer). Once a certain macro will then hang out and where it can not be expected. The same thing behaves like any other function. Her even Intellisense sees and autodopsy! :).


Answer 2, Authority 31%

In MSVC there is a great macro: _countof () . It is just unfolding in the design of the type of SizeOF (Array) / Sizeof (Array [0])


Answer 3, Authority 15%

It is possible that there is a similar macro in some kind of library, but there is no such thing in the standard. Yes, and what prevents from writing the macro myself so much !?

PS: For a short arrays with a constant length of a more correct way, it does not exist.


Answer 4

# include & lt; iostream & gt;
Using Namespace STD;
INT MAIN () {
 int n = 3;
 int v [n];
 COUT & LT; & LT; SizeOF (V) & LT; & lt; Endl;
 COUT & LT; & LT; SizeOF (V) / SizeOF (Int);
}

Pretty simple problem solving, not?

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions