a[14]={0}?

This is a discussion on a[14]={0}? within the C++ Programming forums, part of the General Programming Boards category; Hi! I've seen in some books notation like : Code: a[14]={0}; char a[28]={'#'} What does this do? Thanks!...

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    24

    a[14]={0}?

    Hi! I've seen in some books notation like :
    Code:
    a[14]={0};
    char a[28]={'#'}
    What does this do? Thanks!

  2. #2
    User
    Join Date
    Jan 2006
    Location
    Canada
    Posts
    498
    That does not work because you are redifining "a"; try it; you will end up with a compiler error. I have no idea why they would do that.

    Unless those are 2 different lines of code (ie, in a different program). In that case, it probably fills the first element of the array with the charecter.

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    24
    yeah they are two separate codes. So it only fill the first element?

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,636
    So it only fill the first element?
    Not quite. In the case of:
    Code:
    int a[14] = {0};
    the array is zero initialised, i.e. all 14 elements will be set to 0.
    For the string:
    Code:
    char b[28] = {'#'};
    the first character is set to '#', the rest are left as null characters.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Dec 2005
    Posts
    24
    Thanks for the help

  6. #6
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Hi,

    Just by way of further explanation: if you use an initializer list when you declare an array, i.e.:
    Code:
    int nums[3] = {1, 2};
    and your initializer list does not contain the same number of elements as the size of the array, the remaining elements in the array will be automatically initialized to 0. 0 will be converted to the appropriate type for the array, e.g. a 0 for a char array is the '\0' character. So you can initialize a whole array to 0 doing this:

    int char[20] = {0};

    The first element is initialized to 0 or a '\0' character, and since the initializer list doesn't contain values for the rest of the array, the remaining elements are automatically initialized to '\0'. Now, if you do this:

    char a[28]={'#'};

    That assigns '#' to the first element in the array, and since the initializer list doesn't contain values for the rest of the array, the remaining elements are automatically initialized to '\0'.
    Last edited by 7stud; 04-05-2006 at 01:46 PM.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21