1

I'm reading "Sams Teach Yourself C++ in One Hour a Day" and get stuck with "Lesson 4". It says that I can initialize all elements of multidimensional array with the following code:

int x[n][m] = {1};

But as I understand it's wrong. This code creates array with only one element (x[0][0]) equals 1. Is it a mistake in the book or what?

4
  • 2
    Can you provide a direct quote just to make sure you didn't misunderstand it? Commented Aug 1, 2018 at 18:19
  • Show the definition of n and m. Commented Aug 1, 2018 at 18:19
  • 2
    Sounds like you could use a better C++ book Commented Aug 1, 2018 at 18:20
  • Although books like that might be a better fit for your learning style, having a solid reference is not optional. C++ is an unforgiving language so it's important to have a manual that you can consult tha explains things in depth, not just superficially. Commented Aug 1, 2018 at 18:22

1 Answer 1

8

Well, this declaration will indeed initialize all elements of the array. However, only element x[0][0] will get initialized to 1. The remaining elements (if any) will get initialized to 0.

So, formally the book is right (if you quoted it correctly). You simply misinterpreted what it said.

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

7 Comments

@tadman: It certainly does :) However, the OP's wording seems to suggest that there are other elements in the array.
Certainly! Any C++ book that spends a lot of time talking about C arrays, though, is immediately suspect.
Thanks for answer:) So this behavior only works if you specify zero?
@Lev Zakharov: Not sure what you mean by "works". If you want to initialize all elements to the same value, then yes, it only works for zero. Otherwise, it works as I described above. In C++ you can simply say int x[n][m] = {} or int x[n][m]{} to zero-out everything.
@tadman: That's false. C++, just like C, follows the "All-Or-Nothing" principle in aggregate initialization. When you supply explicit initializer for just a portion of the aggregate, the rest invariably gets default-initialized for you. In C the = { 0 } initializer is well-known as a universal/idiomatic way to zero-initialize anything.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.