1
float minTime[7]={FLT_MAX};
    for(int i=0;i<7;i++)
        cout << "Min: " << minTime[i] << endl;

Why do I get in the following output :

Min: 3.40282e+038
Min: 0
Min: 0
Min: 0
...

Shoudln't all have the same value as the first one? As it is refered here: C++ Notes

1
  • 1
    From your link: Missing initialization values use zero If an explicit array size is specified, but an shorter initiliazation list is specified, the unspecified elements are set to zero. Commented Mar 13, 2011 at 17:21

3 Answers 3

4

Your linked page says "...the unspecified elements are set to zero."

This is correct; as such, only the first element in your array was specified to be FLT_MAX, the rest are initialized to zero. If you want to set them all to the same value you can use a for-loop, or more succinctly:

std::fill_n(minTime, 7, FLT_MAX);

As a warning, C++ is a hard language. This means lots of people have lots of misinformation, and this is especially easy to find on the internet. You'd be better off learning from a book on our list. (And yes, the ones not on our list are so because they too contain misinformation!)

Sign up to request clarification or add additional context in comments.

1 Comment

@doubter: That's okay, it'll happen again and again to all of us. :)
2

Shoudln't all have the same value as the first one?

Nopes! When an array is partially initialized the non-initialized array elements are value initialized (zero-initialized in this case).

C++03 Section 8.5.1/7

If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized (8.5).
[Example:

struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. ]

3 Comments

But that wasn't if I'd did: float miniTime[7]={FLT_MAX,FLT_MAX} and the remaining 5 would be 0? If I only set one of the elements all should be the same, or not?
Technically, the rest of the elements are value-initialized, not zero-initialized. Not that there is any difference for floats :)
@Armen : Yes! Added relevant text from the standard.
1

No, only first value is initialized with the supplied value, other values are value initialized as per standard.

1 Comment

As per standard, they are value-initialized, not default initialized. Not that there is any difference for POD types, including floats

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.