Thread: initializing an array at declaration

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    808

    initializing an array at declaration

    if i have an array with 4 elements set to 0 i could declare it like this
    Code:
    int my_array[5] = {0};
    however suppose i want to declare it with all the elements set to 100 why cant i do this
    Code:
    int my_array[5] = {100};
    if i do the latter i sometimes get a warning that all elements might not be set even if i don't only the first element is set i have to declare and initialize it like this
    Code:
    int my_array[5] = {100,100,100,100,100};
    is this just the way it is and if i have an array with lots of elements i would either have to hard code them all or use a for loop
    many thanks
    coop

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    When you're using an initializer list, every element that isn't explicitly defined defaults to zero.

    Indeed, if you want anything other than zero, you either need to hardcode it or set it with a for loop.

    GCC specifically has an extension that lets you specify a range, if you don't care about compiler portability:
    Code:
    int my_array[5] = { [0 ... 4] = 100 };
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Apr 2019
    Posts
    808
    ok dumb question time im sure its just a coincidence in the example (because you used mine) you have three fullstops ([0 ... 4]) do the fullstops stand for 1, 2 and 3 or is it just you use three fullstops
    sorry to be thick
    coop

  4. #4
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Oh, my bad, I didn't clarify. It's a specifier that (in this context) defines a range, and it has a formal name, "ellipsis". It's always "...", three full-stops with no white-space in-between.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Initializing an array with -1
    By RyanC in forum C Programming
    Replies: 10
    Last Post: 12-04-2018, 05:35 PM
  2. problem initializing a double array for large array
    By gkkmath in forum C Programming
    Replies: 4
    Last Post: 08-25-2010, 08:26 PM
  3. initializing array .
    By transgalactic2 in forum C Programming
    Replies: 24
    Last Post: 04-20-2009, 09:56 AM
  4. Initializing an Array
    By IdioticCreation in forum C++ Programming
    Replies: 9
    Last Post: 04-30-2007, 03:49 PM
  5. help on initializing array
    By neversell in forum C Programming
    Replies: 6
    Last Post: 06-30-2002, 05:07 AM

Tags for this Thread