6

Have a look at this code snippet

struct S{ int i; int j;};

int main()
{
   assert(S().i ==  S().j) // is it guaranteed ?
}

Why?

Bollinger
  • 63
  • 3

3 Answers3

10

is it guaranteed ?

Yes it is guaranteed. The values of S().i and S().j would be 0. () implies value initialization. (that means i and j would be zero-initialized because S is a class without a user defined default constructor)

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • In particular, adding `S() {}` (a do-nothing user-defined ctor) to `struct S` will cause `i` and `j` to be left uninitialised, meaning the `assert()` is likely to trigger. – j_random_hacker Dec 07 '10 at 17:16
0

From C++ Standard ISO/IEC 14882:2003(E) point 3.6.2

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place.

So this is valid as both variables are zero-initialized.

j_kubik
  • 6,062
  • 1
  • 23
  • 42
-1

Technically, yes. They will be initialized to 0 (at least under a non-debug build for most compilers. Visual Studio's compiler will usually initialize uninitialized variables to a specific pattern in debug builds).

However, if you were sitting in a code review, don't be surprised if you get yelled at for not explicitly initializing your variables.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42