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?
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.
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++.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With