Thread: a[14]={0}?

  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
    499
    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
    28,413
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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,663
    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