Monday, March 29, 2010

PostTwiceDaily2 03/29/2010 (p.m.)

  • tags: no_tag

    • Getting an array length in C++ might be less trivial:



      int arr[17];
      int arrSize = sizeof(arr) / sizeof(int);


      Notice that sizeof(arr) returns the array size in bytes, not its length, so we must remember to divide its result with the size of the array item type (sizeof(int) in the example above).


      I want to show you this nice C++ macro which helps us getting an array length in another and better way:



      template<typename T, int size>
      int GetArrLength(T(&)[size]){return size;}


      This is how to use it:



      template<typename T, int size>
      int GetArrLength(T(&)[size]){return size;}

      void main()
      {
      int arr[17];
      int arrSize = GetArrLength(arr);
      }


      aarSize will be equal to 17. Enjoy!


Posted from Diigo. The rest of my favorite links are here.