Thread: initialize an array of strings

  1. #1
    Registered User
    Join Date
    Jul 2009
    Location
    Croatia
    Posts
    272

    initialize an array of strings

    Is it more correct to do it with constructors, or just passing a const char pointer?

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
          string months[] = {
                 string("January"),
                 string("February"),
                 string("March"),
                 string("April"),
                 string("May"),
                 "June",
                 "July",
                 "August",
                 "September",
                 "October",
                 "November",
                 "December"
          };
          for(int i = 0; i < sizeof(months) / sizeof(months[0]); i++)
             cout << months[i] << endl;
          
          
          return 0;
    }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    It is "correct" to do it either way. The difference is that wrapping a string literal around a constructor will make the conversion explicit (anyone sees and knows it occurs), where otherwise it is implicit. Explicit conversions are exactly what they say on the tin and this is why people prefer them.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do you use variable to initialize array size?
    By yougene in forum C Programming
    Replies: 11
    Last Post: 09-04-2007, 02:50 PM
  2. Build an array of strings dynamically
    By Nazgulled in forum C Programming
    Replies: 29
    Last Post: 04-07-2007, 09:35 PM
  3. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  4. remove strings from array
    By ipe in forum C Programming
    Replies: 2
    Last Post: 01-12-2003, 04:53 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM