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?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Lev Zakharov
  • 2,409
  • 1
  • 10
  • 24
  • 2
    Can you provide a direct quote just to make sure you didn't misunderstand it? – Rakete1111 Aug 01 '18 at 18:19
  • Show the definition of `n` and `m`. – R Sahu Aug 01 '18 at 18:19
  • 2
    Sounds like you could use a better [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Aug 01 '18 at 18:20
  • Although books like that might be a better fit for your learning style, having a solid [reference](http://www.stroustrup.com/4th.html) 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. – tadman Aug 01 '18 at 18:22

1 Answers1

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • @tadman: It certainly does :) However, the OP's wording seems to suggest that there are other elements in the array. – AnT stands with Russia Aug 01 '18 at 18:24
  • Certainly! Any C++ book that spends a lot of time talking about C arrays, though, is immediately suspect. – tadman Aug 01 '18 at 18:25
  • Thanks for answer:) So this behavior only works if you specify zero? – Lev Zakharov Aug 01 '18 at 18:25
  • 2
    @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. – AnT stands with Russia Aug 01 '18 at 18:26
  • I'm not certain the remaining elements are initialized to 0. Their values are undefined, aren't they? – tadman Aug 01 '18 at 18:27
  • @AnT The book says: "Initializing all elements to zero could not be any simpler...". So I assumed that this rule applies to other values. – Lev Zakharov Aug 01 '18 at 18:28
  • 3
    @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. – AnT stands with Russia Aug 01 '18 at 18:29
  • @ant Thanks for clarifying. – tadman Aug 01 '18 at 18:29