Search

6.2 — Arrays (Part II)

This lesson continues the discussion of arrays that began in lesson 6.1 -- Arrays (part I)

Initializing fixed arrays

Array elements are treated just like normal variables, and as such, they are not initialized when created.

One way to initialize an array is to do it element by element:

However, this is a pain, especially as the array gets larger.

Fortunately, C++ provides a more convenient way to initialize entire arrays via use of an initializer list. The following example is equivalent to the one above:

If there are more initializers in the list than the array can hold, the compiler will generate an error.

However, if there are less initializers in the list than the array can hold, the remaining elements are initialized to 0 (or whatever value 0 converts to for a non-integral fundamental type -- e.g. 0.0 for double). This is called zero initialization.

The following example shows this in action:

This prints:

7
4
5
0
0

Consequently, to initialize all the elements of an array to 0, you can do this:

In C++11, the uniform initialization syntax can be used instead:

Omitted length

If you are initializing a fixed array of elements using an initializer list, the compiler can figure out the length of the array for you, and you can omit explicitly declaring the length of the array.

The following two lines are equivalent:

This not only saves typing, it also means you don’t have to update the array length if you add or remove elements later.

Arrays and enums

One of the big documentation problems with arrays is that integer indices do not provide any information to the programmer about the meaning of the index. Consider a class of 5 students:

Who is represented by testScores[2]? It’s not clear.

This can be solved by setting up an enumeration where one enumerator maps to each of the possible array indices:

In this way, it’s much clearer what each of the array elements represents. Note that an extra enumerator named MAX_STUDENTS has been added. This enumerator is used during the array declaration to ensure the array has the proper length (as the array length should be one greater than the largest index). This is useful both for documentation purposes, and because the array will automatically be resized if another enumerator is added:

Note that this “trick” only works if you do not change the enumerator values manually!

Arrays and enum classes

Enum classes don’t have an implicit conversion to integer, so if you try the following:

You’ll get a compiler error. This can be addressed by using a static_cast to convert the enumerator to an integer:

However, doing this is somewhat of a pain, so it might be better to use a standard enum inside of a namespace:

Passing arrays to functions

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!

The following example illustrates this concept:

before passValue: 1
after passValue: 1
before passArray: 2 3 5 7 11
after passArray: 11 7 5 3 2

In the above example, value is not changed in main() because the parameter value in function passValue() was a copy of variable value in function main(), not the actual variable. However, because the parameter array in function passArray() is the actual array, passArray() is able to directly change the value of the elements!

Why this happens is related to the way arrays are implemented in C++, a topic we’ll revisit once we’ve covered pointers. For now, you can consider this as a quirk of the language.

As a side note, if you want to ensure a function does not modify the array elements passed into it, you can make the array const:

sizeof and arrays

The sizeof operator can be used on arrays, and it will return the total size of the array (array length multiplied by element size). Note that due to the way C++ passes arrays to functions, this will not work properly for arrays that have been passed to functions!

On a machine with 4 byte integers and 4 byte pointers, this printed:

32
4

(You may get a slightly different result if the size of your types are different).

For this reason, be careful about using sizeof() on arrays!

Note: In common usage, the terms “array size” and “array length” are both most often used to refer to the array’s length (the size of the array isn’t useful in most cases, outside of the trick we’ve shown you above). In these tutorials, we’ll try to use the term “length” when we’re talking about the number of elements in the array, and “size” when we’re referring to how large something is in bytes.

Determining the length of a fixed array

One neat trick: we can determine the length of a fixed array by dividing the size of the entire array by the size of an array element:

This prints:

The array has 8 elements

How does this work? First, note that the size of the entire array is equal to the array’s length multiplied by the size of an element. Put more compactly: array size = array length * element size.

Using algebra, we can rearrange this equation: array length = array size / element size. sizeof(array) is the array size, and sizeof(array[0]) is the element size, so our equation becomes array length = sizeof(array) / sizeof(array[0]). We typically use array element 0 for the array element, since it’s the only element guaranteed to exist no matter what the array length is.

Note that this will only work if the array is a fixed-length array, and you’re doing this trick in the same function that array is declared in (we’ll talk more about why this restriction exists in a future lesson in this chapter).

Indexing an array out of range

Remember that an array of length N has array elements 0 through N-1. So what happens if you try to access an array with a subscript outside of that range?

Consider the following program:

In this program, our array is of length 5, but we’re trying to write a test score into the 6th element (index 5).

C++ does not do any checking to make sure that your indices are valid for the length of your array. So in the above example, the value of 13 will be inserted into memory where the 6th element would have been had it existed. When this happens, you will get undefined behavior -- For example, this could overwrite the value of another variable, or cause your program to crash.

Although it happens less often, C++ will also let you use a negative index, with similarly undesirable results.

Rule: When using arrays, ensure that your indices are valid for the range of your array!.

Quiz

1) Declare an array to hold the high temperature (to the nearest tenth of a degree) for each day of a year (assume 365 days in a year). Initialize the array with a value of 0.0 for each day.

2) Set up an enum with the names of the following animals: chicken, dog, cat, elephant, duck, and snake. Put the enum in a namespace. Define an array with an element for each of these animals, and use an initializer list to initialize each element to hold the number of legs that animal has.

Write a main function that prints the number of legs an elephant has, using the enumerator.

Quiz answers

1) Show Solution

2) Show Solution

6.3 -- Arrays and loops
Index
6.1 -- Arrays (Part I)

229 comments to 6.2 — Arrays (Part II)

  • Chassz

    This is the solution I came up with for excercise 2, any comments or things I should do differently?

  • Kio

    A longer version "program" for the Quiz 1.

    • Kio

      function "initilizeTemperature" is obsolete because it's every element is set to 0.0. Redundant code by my side.

    • Hi Kio!

      * Line 10, 17: Uniform initialization
      * Magic number 365. Define a constant
      * Line 19: You only need to call @std::setw once before the loop
      * "indexDay" is poorly named, because it's not an index. "dayOfYear" or similar seems more obvious.
      * You're using the same name style for variables and functions. This can lead to confusion.

      Other than that, your code is well structured. Keep it up!

      • Kio

        Thnx mate. Noted.
        Can you provide, naming convention for functions and variables. Function and variables both starts with lowercase name. I'm using the camelCase method. How to dinstict one from another.

        • I like hungarian notation ( https://en.wikipedia.org/wiki/Hungarian_notation#Examples ). There are many variations of it. I write functions names just like you do and only prefix variables.

          • Kio

            Hey mate,
            At the moment I'm not seeing bigger picture.
            "You're using the same name style for variables and functions. This can lead to confusion."
            Can you provide example, how to improve.
            Btw, can you recommend a website for cpp standard library, that is well writteen.
            Thnx.

            We should create discord group, chat.

            • > Can you provide example, how to improve
              I linked a list of examples on wikipedia, I don't know what more you're looking for.

              > recommend a website for cpp standard library
              http://www.cplusplus.com/reference/

  • Terra'Navis

    Hi i was wondering if anyone could explain why double is used in the first quiz question over float, if we only want one tenth accuracy then why would Alex use double if it allocates more memory than float?

    • Alex

      Best practice is to prefer double over float, unless you have a specific reason to do otherwise (e.g. you are optimizing for memory usage, which really only matters when you have millions of elements). In most cases, it's better to favor precision over speed/memory (and there's no guarantee that floats are actually faster).

      Also, double, not float, is the default floating point type in C++.

  • Daniel Wallace

    The start of the "sizeof and arrays" section appears to contain a formatting error:

    "
    The sizeof operator can be used on arrays, and it will return the total size of the array (array length multiplied by element size). Note that due to the way C++ passes arrays to functions, this will _not_ work properly for arrays that have been passed to functions!
    "

    It looks like "_not_" is formatted in a way that is trying to make it either bold or italics but is not converting it to the proper format.

  • TC

    Dear Alex and Nas,

    Thanks for taking time to answer all the questions. I am really greatfull this wonderful tutorial.

    I notice that the enum identifer has nothing to do with the array indexing regarding accessing the array element.
    Just wander why this is the case.

    Best regard,

    TC

    • Alex

      Normal enums dump their enumerators into the enclosing namespace, so we don't have to use the enum name to access the enumerators when we're using them at literals (which is all we're doing here).

      However, if we wanted to define a variable to hold a value of the enumerated type, we'd have to use the enum's name:

  • Arrays are always fun but multidimensional arrays can be more complex

    Will you be covering multidimensional arrays and vectors later?

    • Hi Nigel!

      > multidimensional arrays
      Lesson 6.5 and 6.14

      > vectors
      How do you know of vectors? Neither C# nor C have them.
      But yes, lesson 6.16

      • <How do you know of vectors? Neither C# nor C have them.> because I get regular updates from codeproject and they mentioned them briefly plus they area function in mathematics that I recall from my schooldays (actually, my main job involves a lot of physics).

        • > they area function in mathematics
          Different vectors. C++ named them badly. C++ vectors are just lists of any type (like an array, but easier to use), they have nothing to do with math.

  • AmarCODTV

    Would it work if we dereference the pointer?
    Can't test it myself, because I'm not at home...

    • Alex

      No. If array decays to a pointer that points to the first element of the array, then *array is the value of the first element of the array. Printing the sizeof(*array) prints the size of the first element of the array.

  • Hi Alex!

    @main is missing a return statement in the section "Arrays and enum classes".

  • Nguyen

    Hi Alex & nascardriver,

    I have a question about the function calls in the program under the sections of "Passing arrays to functions" & "sizeof and arrays".  

    These function calls are:
    passArray(prime);// line 26.  The called function: void passArray(int prime[5])
    printSize(array);// line 10.  The called function: void printSize(int array[])

    I am wondering why these function calls were not written as
    passArray(prime[5])
    printSize(array[])

    Thanks, Have a great day.

    • You're reading the fifth element element from @prime, which is an int. @passArray wants an int-array, not an int, so it doesn't work.

      This isn't valid cpp syntax.

  • Infinite

    For the answer to the first quiz, could we have initialized it with {} instead of {0.0}

    • Hi Infinite!

      Yes, that's the better solution in my opinion. The 0.0 is the curly braces only affects the first element of the array, the other 364 elements remain untouched.
      Also, uniform initialization should be used

      Empty curly braces zero-initialize arrays.

  • Suprith

    To access the enum type, first we have to define enum type variable inside the main() right.? Without which how can we writeint testScores[MAX_STUDENTS]; // allocate 5 integers
        testScores[STAN] = 76;

  • Samira Ferdi

    Hello, Alex and nascardriver.

    Can I do this?

    In best practices view, is it good?

    • nascardriver

      Hi Samira!

      You can, but it's not good practice.
      Your enum might not be contiguous, so you could have wasted space in there and the initialization isn't easy to follow.
      An @std::map is better:

      @std::map isn't covered on learncpp. If you're having trouble understanding it you can revisit it after @std::array and @std::vector have been covered later this chapter.

      References
      * std::map - http://www.cplusplus.com/reference/map/map/

  • RelearningCGuy

    Regarding static and automatic memory allocation and arrays: Does C++11 or higher guarantee safe handling of an array's memory space if the array is created in a function that then terminates?  For example, if a void function creates a new array and inserts that pointer into an opening on an existing array to create some kind of nested table. When the void function terminates, is the memory space of the array it created preserved or is it freed from tracking/protection?

    • nascardriver

      Hi RelearningCGuy!

      The lifetime of the to-be-inserted array will not be extended. If you want to replace a sub-array you should first delete any existing data and allocate the new array dynamically.

      References
      * Chapter 6 - Arrays, Strings, Pointers, and References (You'll need all of it, don't skip chapters)

      • RelearningCGuy

        I'm definitely not going to be skipping anything -- I just wanted clarification on that one point because I wasn't sure if C++ would continue to preserve that memory since it was attached then to a still-active array. I appreciate the additional info!

  • Joe

    Hi guys,

    I am trying to input characters from cin individually into the elements of a vector array.
    so far what I have done is to create an array with as many elements as characters typed, but each element is holding all the information typed instead of individual characters.

    I have tried making my array a char array but other errors keep popping up.  so far this is the code that works.

    I am using code::blocks at the moment

    I am going to try other things while I wait.  Hopefully I figure it out soon.

    Thank you for your time.

    • nascardriver

      Hi Joe!

      First off: Initialize your variables with uniform initialization.

      Solution

      References
      * Lesson 6.11 to 6.12 - References
      * Lesson 16.3 - STL iterators overview
      * std::vector::vector range(3) - http://www.cplusplus.com/reference/vector/vector/vector/
      * std::string::begin - http://www.cplusplus.com/reference/string/string/begin/
      * std::string::end - http://www.cplusplus.com/reference/string/string/end/

  • Tyler

    When I did your example 2 I used a header file and did namespace and also an enum class. This did not work. Why?

    Animals is the namespace, ANIMAL is the enum class. Just curious at this point I was able to make it work fine by using only enum class no namespace or namespace and regular enum.

    • nascardriver

      Hi Tyler!

      An enum class enumerator cannot implicitly be converted to an int, you need to cast it.

      Please post your code and error message when you have problems to make spotting the error easier.

  • Sai Krishna (SK)

    I planned on writing a program with different ways of passing arrays but then, I encountered a scary error...
    _____________________________________________________________
    Error message:

    2
    *** stack smashing detected ***: ./a.out terminated
    2Aborted (core dumped)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    (I used Ubuntu 16.04, 64 bit, os and I use its terminal to compile and run cpp programs and use vim editor for writing programs)

    • Sai Krishna (SK)

      It came as a run time error...
      That error showed up right after I began running the code...

      Honestly, I am perplexed to see such new terms that appeared...
      Please help :"(.

    • nascardriver

      Hi Sai!

      In @inc and @ris @i can go up to 10 which is an invalid index, because your array only has 10 elements.

      * Don't use 'using namespace'
      * Don't use recursion unless it makes your code a whole lot easier
      * Line 15: Don't use @i while modifying it. Your compiler should've printed a warning
      * Use uniform initialization

      • Sai Krishna (SK)

        Ok, I followed your instructions. They seem to be very helpful so, I'll keep them in mind. Thanks a lot 😀

        Also, what does stack smashing detected mean? Seems quite dangerous.

        • nascardriver

          Your compiler added some runtime checks to make sure you're not accessing invalid indexes. If you disable those checks your program would crash without a message, making it harder to figure out what's happening.

  • For the quiz 2     Array (PART 2)          ,  why don't we just type    
    double temperature[365] = { 0 };
    0 will automatically changed to 0.0 due to implicit type conversion, isn't it?

    • nascardriver

      Hi Aron!

      Yes, your compiler will choose the right type for you if you just type 0, but you should use the numbers that fit the type. There's no super cool reasoning behind it, it just makes your code look more like you know what you're doing.

      Also, uniform initialization is preferred.

  • this weird error keeps popping up and i dont know where i messed up.

    Severity    Code    Description    Project    File    Line    Suppression State
    Error    C2440    '=': cannot convert from 'initializer list' to 'int'    Enumarrays    f:\visual studio solutions-projects\enumarrays\enumarrays\enumarrays.cpp    22

    • nascardriver

      Hi Ali!

      • this time i got it!

        • nascardriver

          Hi Ali!

          Good job solving the quiz!

          Practice for you, because you're having trouble with function parameters:
          Write a function that takes an @Animal as parameter and returns the amount of legs this animal has.

          Should print
          "A snake has 0 legs"

          • it was easy considering you wrote the most for me 🙂 but why do I feel like this wasn't the way done you asked from me?

            • nascardriver

              > it was easy
              Apparently not

              Your compiler should have warned you about both issues, don't ignore them.

              > why do I feel like this wasn't the way done you asked from me?
              I don't understand

              • is it better noow?

                • nascardriver

                  Better, yes, but your compiler is still warning you. Don't ignore compiler warnings.

                  Line 33: warning: control reaches end of non-void function

                  @getNumberOfLegs always has to return a value.

              • it must be ok now 🙂

  • Peter Baum

    The problem I have with quiz 1 is that when I try to output the result I just get "0" rather than "0.0".  How do I force cout to output one digit to the right of the decimal point so that it is clear the result is not an integer?  (I know the problem is not with my initialization, because using a value of 0.1 works fine.)

    Also, following the suggestion in the lesson, I would have thought the answer should be:

    and when I saw the given solution, I wondered if maybe that approach would be a way to copy a default value from the first element of the array to all the other elements.  No such luck!  However, it did made me wonder if there was another way to set every value at 0.1 at compile time (without explicitly entering all these values into an initialization list)?

    It also occured to me that saying the default value for initialization is 0 is ambiguous, because it isn't clear what happens for non-integer data types.  Maybe the lesson can make this clearer.

    • nascardriver

      Hi Peter!

      > "0" rather than "0.0"
      Here are some formatting options: http://en.cppreference.com/w/cpp/io/manip/fixed (Especially std::fixed)
      Not exactly what you were looking for but the closest it gets without writing a custom formatting function.

      > another way to set every value at 0.1 at compile time
      Nope. Large arrays are usually dynamically allocated at runtime (Lesson 6.9a) anyway, so C++ isn't missing out on too much by not having a feature for this (It's probably possible with macros and templates, but that will get messy).

      • Peter Baum

        Thanks.  That is very helpful.  

        I discovered that the function printf() (originally in C and available in C++) would do what I wanted very easily.  Some of the "improvements" they made to C++ relative to C are very disappointing.  Here is a link that compares printf with cout:

        https://stackoverflow.com/questions/2872543/printf-vs-cout-in-c

        and the first answer is excellent.

  • Peter Baum

    In the section "Determining the length of a fixed array" I suggest moving the helpful paragraph (at the end) comprising

    "In common usage, the terms “array size” and “array length” are both most often used to refer to the array’s length (the size of the array isn’t useful in most cases, outside of the trick we’ve shown you above). In these tutorials, we’ll try to use the term “length” when we’re talking about the number of elements in the array, and “size” when we’re referring to how large something is in bytes."

    at least to the beginning of the section, before confusion starts, or perhaps even earlier in another section.

  • Dian Jin

    That South Park reference in the example...am I the only one that gets it lol..

    Thanks Alex! Awesome guide and tutorial!!!!

    You are one awesome human being!!

  • Jim

    Another "initializer" question:
    You mentioned that leaving out a value when an array is created (int myArray[] - { a list of 14(for example) or less integers}) would "let initializer list set length of the array".

    We then see an example of the dangers of using sizeof on an array where you put 8 integers in an initializer list. However, the sizeof(array), immediately after its creation, outputs "4".

    I do not understand why "a machine with 4 byte integers and 4 byte pointers" affects the length/sizeof value. Since an array is actually pointed to (rather than copied like other variables), the address size (as the size of a memory location) makes sense. ;+)

    Is this the whole point about _not_ using sizeof() with arrays, even if there is a trick/hack? My particular system/OS happens to be 64-bits, so I got an output of 32 and 8.

    Looks like I should add this to the list of things NOT to do, just below arguing with my wife...

    PS: My compiler did issue a warning: "Sizeof on array function parameter will return size of 'int *' instead of 'int []'"

    Thanks!

    • Alex

      Part of the problem here is we're seeing a phenomena that I haven't explained (the fact that arrays decay into pointers when evaluated) because I haven't explained pointers yet.

      So when you define a fixed array of 4-byte integers with 8 elements, sizeof(array) will return 32 (8 elements * 4 bytes per element). The size of a pointer is irrelevant here.

      However, if you pass this array to a function, the array decays to a pointer. Then when you do sizeof(array), you're actually asking the compiler for the size of the pointer (not the array), so you'll get 4 or 8 bytes depending on whether you're doing a 32 or 64 bit app.

      Using sizeof with fixed arrays is fine so long as you're careful to do so only with the actual fixed array, and not an array that has decayed into a pointer.

      • Jim

        I think I was beginning to suspect (that's still short of "knowing"!) when I read some in a book about C++. I knew the "math" was not valid using the two values we were getting. Your explanation makes it simple... again! ;+)

  • Jim

    Man! I miss a few days and I almost immediately hit confusion!
    Near the very beginning of this lesson:
    "Fortunately, C++ provides a more convenient way to initialize entire arrays via use of an initializer list. The following example is equivalent to the one above:"

    ...
    "In C++11, the uniform initialization syntax can be used instead:"

    Please tell me that "uniform initialization" is just another way of saying "initializer list".

    • Alex

      They aren't the same thing. Uniform initialization is a statement of this form:

      type identifier { initializer };

      e.g. double d { 2.3 };

      C++11 introduces list initialization, which uses an initializer list (the {2, 3, 5, 7, 11}). You can initialize a fixed array with an initializer list using uniform initialization:

      int prime[5] { 2, 3, 5, 7, 11 };

      or with other initialization forms, such as copy initialization:

      int prime[5] = { 2, 3, 5, 7, 11 };

      • Jim

        Thanks! I _finally_ see the difference in the two lines: "="  Perhaps you add "copy" to the remark text so that people who need glasses, like me, can read what they can't see! BTW, I have an appointment with my eye doctor next week... :blush:
        "You can lead a horse to the computer, but I'm not sure you can teach him C. On the other hand, I know a great teacher..."

  • Oskar Ramirez

    Hi Alex.  I'm new to programming so I want to start off by saying thank you for being so thorough and so awesome.  I hope to make you proud one day.  In the mean time, can you take a look at my code?  I was able to work it into a manner similar to your solution, but in this example I attempted to call in the input from another function.  Unfortunately it only prints the array when I use break, or works randomly with continue, while looping forever.  Please tell me what i'm wrong.  Any help would be appreciated.
    [int enterNumber(int guess)
    {
    while (1)
    {
    std::cout << "Enter number between 1 and 9 " <> x;

    if (std::cin.fail()) // has a previous extraction failed?
    {
    // yep, so let's handle the failure
    std::cin.clear(); // put us back in 'normal' operation mode
    std::cin.ignore(32767, 'n'); // and remove the bad input
    }
    else if (x > 9)
    {
    std::cin.clear();
    std::cin.ignore(32767, 'n');
    std::cout << "Your number is too high dude" << std::endl;
    }
    else if (x < 1)
    {
    std::cin.clear();
    std::cin.ignore(32767, 'n');
    std::cout << "You're wasting my time n";
    }

    else
    {
    std::cin.ignore(32767, 'n');
    std::cout << "4, 6, 7, 3, 8, 2, 1, 9, 5 " << std::endl;
    return x;
    }
    }

    }

    int main()
    {
    int array[] = { 4, 6, 7, 3, 8, 2, 1, 9, 5 };
    const int arrayLength = sizeof(array) / sizeof(array[0]);

    for (int index = 0; index < arrayLength; ++index)
    {
    int x = enterNumber(index);
    if (x == array[index])

    std::cout << "You entered element " << x << " with index " << index << std::endl;
    break;
    }

    return 0;
    }]

  • James carron

    You said that "Note that this will only work if the array is a fixed-length array" but you used   int array[] = { 1, 1, 2, 3, 5, 8, 13, 21 };, the array doesn't have a specified length?

  • WOW. this is a very complete explanation.

    Hey alex, you're awesome. thanks for making great tutorial.

  • Wunna

    Some other questions,

    In the above code you wrote. Would the function make the array constant afterward?(I mean in main() after calling this function)
    And are the array parameters the copy like the function parameters?

    • Alex

      > Would the function make the array constant afterward?(I mean in main() after calling this function)

      No, the constness of the parameter only affects array access through that parameter. The actual array is unaffected.

      > And are the array parameters the copy like the function parameters?

      I don't understand what you're asking here.

    • Wunna

      I mean would they just implicitly convert any enum or variable being put as parameters into integer?
      I mean for example prime[++x] would cause the actual x to be incremented?

  • Wunna

    I have a little question with this code

    There, why would you bother putting enum into a namespace.
    It makes no sense to me and just making it more of work to be done.
    As I learned from you that enum classes wouldn't implicitly convert into integer so they should be preferred but putting enum into namespace doesn't give the power of enum classes instead having to put namespace's name before enum every time we want to call. Even if it does,it'd still be the same with enum classes and will have to static_cast them which is a pain,right?
    Please explain me why, if you have a good reason.
    Thanks a lot,my teacher.

    • Alex

      It's not strictly necessary to put the enum into the namespace, it just helps keep your global namespace clean. For example, without the namespace, if you defined another enum in the same scope that used the same enumerator in a different context, you'd get a naming conflict. For example:

      STAN will cause a naming conflict because both StudentNames and ChildrenNames are trying to define it in the same place.

      Using an enum in a namespace helps provide the naming cleanliness, but doesn't restrict implicit conversion to integer like an enum class does. In some cases, preventing that implicit conversion is desirable. Here, it's just a pain.

      • Wunna

        Thanks a lot, it's a lot clearer now.

      • Wunna

        But if that's the case,shouldn't we also put enum classes into a namespace too?

        • Wunna

          Or,enum classes don't have any naming conflict with other enum classes at all?

          • Alex

            Enum classes act as their own namespace, so the enumerators are in the namespace of the enum class.

            • Wunna

              Loud and clear,sir.

            • Peter Baum

              So the characteristics have to do with
              1. being or not being your own namespace
              2. possible ambiguous references to the same name (which is where using a namespace might come in)
              3. the ability to use the integer aspect of an enumeration in output or some other operation without a cast

              What confuses me is that I don't understand how these 3 things are related.  Help!

              • Alex

                1) Namespaces, structs/classes, and enum classes all provide a namespacing effect that you can use to help prevent name collisions if you want to use them.
                2) This is directly related to namespacing, so isn't an independent factor.
                3) Enums implicitly convert to an integer, enum classes do not (you have to do so explicitly).

                When using enumerators as array indices, I generally think enums are a better choice than enum classes because the implicit conversion to int is useful. However, defining enumerators at the global scope is generally a bad practice. So you're better off sticking them inside a namespace, class, or struct.

  • Jasper

    Hi Alex, I'd like to create a program that loops through an array of names and grades, and prints something like: "Stan has the highest score: 87", Kenny has the lowest score: 57". I think I need an array that holds both strings and integers but I can't find the correct method. This code I have doesn't work:

    • Alex

      At this point in the tutorial series, I'd use a struct instead of a class. Try this:

      • Jasper

        Thanks! My program works now. Here is the code:

  • Angmar

    Hi,  is there any sugar for creating long arrays liike {0 .. 6} instead of writing {0, 1, 2, 3, 4, 5}

    • Alex

      Nope. If you're okay with assigning values rather than initializing values, you could write a loop to assign values to the array elements rather than list them all out explicitly.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]