Monday, August 17, 2009

c++: operator promotion

The hierarchy used for type promotion in C++ looks like this:

long double (highest)
double
float
unsigned long int
long int
unsigned int
int (lowest)





To initialize a two-dimensional array, it is easiest to use nested braces, with each set of numbers representing a row:
view source
print?
1.int anArray[3][5] =
2.{
3.{ 1, 2, 3, 4, 5, }, // row 0
4.{ 6, 7, 8, 9, 10, }, // row 1
5.{ 11, 12, 13, 14, 15 } // row 2
6.};

When the C++ compiler processes this list, it actually ignores the inner braces altogether. However, we highly recommend you use them anyway for readability purposes.

Two-dimensional arrays with initializer lists can omit (only) the first size specification:
view source
print?
1.int anArray[][5] =
2.{
3.{ 1, 2, 3, 4, 5, },
4.{ 6, 7, 8, 9, 10, },
5.{ 11, 12, 13, 14, 15 }
6.};

The compiler can do the math to figure out what the array size is. However, the following is not allowed:
view source
print?
1.int anArray[][] =
2.{
3.{ 1, 2, 3, 4 },
4.{ 5, 6, 7, 8 }
5.};

Because the inner parenthesis are ignored, the compiler can not tell whether you intend to declare a 1×8, 2×4, 4×2, or 8×1 array in this case.

Just like normal arrays, multidimensional arrays can still be initialized to 0 as follows:
view source
print?
1.int anArray[3][5] = { 0 };

Note that this only works if you explicitly declare the size of the array! Otherwise, you will get a two-dimensional array with 1 row.






* Because references are typically implemented by C++ using pointers, and dereferencing a pointer is slower than accessing it directly, accessing values passed by reference is slower than accessing values passed by value.
7.4 — Passing arguments by address

No comments:

Post a Comment