Array initialization in C ++

Everywhere I look, there are people who argue loudly that uninitialized variables are bad, and of course I agree and understand why - however; my question is, are there any cases where you would not want to do this?

For example, take the code:

char arrBuffer[1024] = { '\0' };

Does NULLing the entire array mean performance impact on the use of the array without initializing it?

+5
source share
10 answers

I assume the initialization of the stack, because static arrays are automatically initialized.
G ++ output

   char whatever[2567] = {'\0'};
   8048530:       8d 95 f5 f5 ff ff       lea    -0xa0b(%ebp),%edx
   8048536:       b8 07 0a 00 00          mov    $0xa07,%eax
   804853b:       89 44 24 08             mov    %eax,0x8(%esp)
   804853f:       c7 44 24 04 00 00 00    movl   $0x0,0x4(%esp)
   8048546:       00 
   8048547:       89 14 24                mov    %edx,(%esp)
   804854a:       e8 b9 fe ff ff          call   8048408 <memset@plt>

So, you are initialized with {'\ 0'} and the memset call is executed, so yes, you have performance.

+10

, . , char arrBuffer[1024] 1024 . , 0 , . , .

, , , . , memcpy , .

+7

, .

, , .

, :

int main (void) {
    int a[1000];
    : :
    for (int i =0; i < sizeof(a)/sizeof(*a); i++)
        a[i] = i;
    : :
    // Now use a[whatever] here.
    : :
    return 0;
}

.

, , .

C , , ( , ), , .

, . , , . ( , , ).

, ( main). , , , .

( ..), , -, . " " :

void x(void) {
    int x[1000];
    ...
}

, x [] . :

void x(void) {
    int x[1000] = {0};
}

1000- memcpy ( , memset ), , , . , , .

+4

Measure!

#include <stdio.h>
#include <time.h>

int main(void) {
  clock_t t0;
  int k;

  t0 = clock();
  for (k=0; k<1000000; k++) {
    int a[1000];
    a[420] = 420;
  }
  printf("Without init: %f secs\n", (double)(clock() - t0) / CLOCKS_PER_SEC);

  t0 = clock();
  for (k=0; k<1000000; k++) {
    int a[1000] = {0};
    a[420] = 420;
  }
  printf("   With init: %f secs\n", (double)(clock() - t0) / CLOCKS_PER_SEC);

  return 0;
}
$ gcc measure.c
$ ./a.out
Without init: 0.000000 secs
   With init: 0.280000 secs
$ gcc -O2 measure.c
$ ./a.out
Without init: 0.000000 secs
   With init: 0.000000 secs
+2

. . , , , . , .

0

: . , , . .

, . : Lint-like, , , , , ( , , ).

0

, , . .

, :

char s[24];
sprintf(s, "%d", int_val);

:

char s[24] = "\0";
sprintf(s, "%d", int_val);

, .

0

. , . , , .

, , - . , .

( ), , . , ? , . - .

, , , .

0

. .

char buffer[1024] = {0};
for (int i = 0; i < 1000000; ++i)
{
  // Use buffer
}

.

for (int i = 0; i < 1000000; ++i)
{
  char buffer[1024] = {0};
  // Use buffer
}

, , 0? , . - , , .

, , , , ?

, 0. , , , . , , .

: 0 ( "0" ), "\ 0".

, .

char buffer[1024] = {0};
for (int i = 0; i < 1000000; ++i)
{
  // Buffer is 0 initialized, so it is fine to call strlen
  int len = strlen (buffer);
  memset (buffer, 'a', 1024);
}

0, strlen 0. 0 0, strlen undefined.

, , , , , ?

0

, , , , , , - .

-2

All Articles