سؤال

Have a look at this code snippet

struct S{ int i; int j;};

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

Why?

هل كانت مفيدة؟

المحلول

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)

نصائح أخرى

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.

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top