Following an example from Scott Meyer's "Modern C++", I'd exploit std::array size deduction with templates. I'm stumbled trying to compile my myUsage function usage.
#include <array> #include <iostream> template <typename T, std::size_t N> constexpr std::size_t arraySize(T (&) [N]) noexcept { return N; } void scottUsage() { int b[5]; std::array<short, arraySize(b)> c; std::cout << arraySize(b) << " = " << c.size() << "\n"; } template <typename T, std::size_t N> void myUsage(T & arr [N]) { for (auto i=0; i<arraySize(arr); i++) std::cout << arr[i] << "\t"; } int main() { scottUsage(); int a[7]; myUsage(a); } So two questions arise:
- (side question) What's
(&)for? Removing would triggererror: creating array of references, which it seems to be forbidden - What's wrong with
myUsagesignature?
myUsage(T (&arr) [N])? The parentheses are important to make it a reference to an array (instead of an array of references).(&varname)uncommon syntax, and I'll be glad to mark as solvedainmain()is an array of uninitialisedint. Printing the elements inmyUsage()- once you fix the typo with the argument - therefore causes undefined behaviour.