I had an array
arr[10]
It tried to access
arr[12]
and program did not do anything until I realized when I switched to vectors. Somewhere I read that if I use [] then program would not give any runtime error again so that I should use std::vector‘s at. But in my program I just used [] and it helped me to spot the problem. It seems [] is enough. Am I right? Also, is there any bound check for arrays for safety?
Some implementations of the C++ library have a debug mode that will throw an exception even when you use the
[]syntax, but this is not specified by the standard. So that may be what you experienced. If you want to be sure you should useat().C++ doesn’t have bounds checking for primitive arrays, however if your compiler supports the newest version of C++ then you can use
std::arrayinstead of primitive arrays, and this container has anat()method just likestd::vector.I’d recommend using
std::arrayeven if you don’t want this feature because primitive arrays have some other problems (e.g. they decay to pointers at the drop of a hat).std::arraybehaves much more consistently (e.g. you can pass them by value to functions or return them and they’ll work correctly whereas writing the obvious syntax to pass an array by value will fail and will instead just pass a pointer).Do yourself a favor and never use primitive arrays.