Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the size of a const array?

Tags:

c++

arrays

c

sizeof

given the following code:

const myStr codesArr[] =  {"AA","BB", "CC"};     

myStr is a class the wraps char*. I need to loop over all the items in the array but i don't know the number of items. I don't want to define a const value that will represent the size (in this case 3)

Is it safe to use something like:

const int size = sizeof(codesArr) / sizeof(myStr);

what to do?

like image 763
Dardar Avatar asked Nov 14 '12 09:11

Dardar


People also ask

What is the size of const variable?

An int type has a range of (at least) -32768 to 32767 but constants have to start with a digit so integer constants only have a range of 0-32767 on a 16-bit platform.

What is the size of const in C?

In C++ the size of the character constants is char. In C the type of character constant is integer (int). So in C the sizeof('a') is 4 for 32bit architecture, and CHAR_BIT is 8. But the sizeof(char) is one byte for both C and C++.

What is sizeof () in C++ array?

It is because the sizeof() operator returns the size of a type in bytes. You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.

What is a const array?

The keyword const is a little misleading. It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.


1 Answers

The safe and clear way to do this is to use std::extent (since C++11):

const size_t size = std::extent<decltype(codesArr)>::value;
like image 135
ecatmur Avatar answered Sep 19 '22 01:09

ecatmur