美文网首页
6.2 Arrays (Part II)

6.2 Arrays (Part II)

作者: Closears | 来源:发表于2017-08-26 03:35 被阅读4次

原完整教程链接:6.2 Arrays (Part II)

1.
// Initialize all elements to 0
int array[5] = { }; 

2.
// Enum classes don’t have an implicit conversion to integer, 
// however standard Enum does.
// So, how to solve this?
//** Use a standard enum inside of a namespace!**
namespace StudentNames
{
    enum StudentNames
    {
        KENNY, // 0
        KYLE, // 1
        STAN, // 2
        BUTTERS, // 3
        CARTMAN, // 4
        WENDY, // 5
        MAX_STUDENTS // 6
    };
}
 
int main()
{
    int testScores[StudentNames::MAX_STUDENTS]; // allocate 6 integers
    testScores[StudentNames::STAN] = 76;
}

3.
Although passing an array to a function at first glance looks just like 
passing a normal variable, underneath the hood, C++ treats arrays differently.

When a normal variable is passed by value, C++ copies the value 
of the argument into the function parameter. Because the parameter 
is a copy, changing the value of the parameter does not change the 
value of the original argument.

However, because copying large arrays can be very expensive, 
C++ does not copy an array when an array is passed into a 
function. Instead, the actual array is passed. This has the side effect 
of allowing functions to directly change the value of array elements!

4.
// Determining the length of a fixed array
int main()
{
    double arr[9] = {};
    int length_of_arr = sizeof(arr) / sizeof(arr[0]);  // <-- Just this line!
    for (int i = 0; i < length_of_arr; i++)
    {
        cout << arr[i] << endl;
    }
    return 0;
}

相关文章

网友评论

      本文标题:6.2 Arrays (Part II)

      本文链接:https://www.haomeiwen.com/subject/stqmdxtx.html