aardvarkk
aardvarkk

Reputation: 15996

C++ self-referencing array?

I accidentally created a bug in a program by self-referencing in an array. Here's a very simplified demo program similar in concept:

#include <iostream>
using namespace std;

int kTest[] = {
    kTest[0]
};

int main() {
    cout << kTest[0] << endl;
}

I was surprised that I received neither a compiler error or even a warning on this code! In my case it ended up producing unpredictable output. Is it accessing garbage memory?

I was curious about under what circumstances this would have well-defined output (if ever!).

Edit: Does it make a difference if kTest is static? What about const? Both?

Upvotes: 19

Views: 1182

Answers (2)

R Sahu
R Sahu

Reputation: 206607

int kTest[] = {
    kTest[0]
};

is similar to, if not exactly same as

int x = x;

It will be undefined behavior, if declared locally in a function.

It seems to be well defined when kTest is a global variable. See the other answer for additional details.

Upvotes: 15

krzaq
krzaq

Reputation: 16421

I'm not so sure this is undefined. Quote from the current draft:

[basic.start.static]/3

If constant initialization is not performed, a variable with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) is zero-initialized ([dcl.init]). Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place.

To me it looks like kTest is already zero-initialized when the dynamic initialization starts, so it may be defined to initialize to 0.

Upvotes: 8

Related Questions