Mark Ludwig
Mark Ludwig

Reputation: 11

C++ initializer/constructor for basic types

Given the following code, to what does junk1 point at the end of the function before return?

static void junkf(void)
{
   static const char s_char = char();
   const char *junk1 = &s_char;
   static const int s_int = int();
   const int *junk2 = &s_int;
}

(Note that this is my unrolling of a function from a template class that substitutes "char" or "int" according to the declaration. I assume that junk2 points to an int with a zero value -- correct?)

What is the "char()" or "int()" construct called in the C++ language? I want to learn more about this construct for basic types, but can't seem to find anything about it. Is this an initializer, or a constructor, or ...?

Thanks!

Upvotes: 1

Views: 118

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385284

At the end of the function, junk1 points to the exact same thing you told it to point to — s_char.

Since junk1 dies at the end of the function, whether s_car lives beyond that is not part of any useful discussion.


Rewriting the question slightly based on comments:

const char c = char();  // what value does `c` have, and why?
const char* ptr = &c;   // what does `ptr` point to?

char() is an expression containing the construction of an anonymous, temporary char. Instantiating a type with an empty constructor argument list performs value-initialisation (§8.5/10). §8.5/7 tell us that, during value-initialisation, since char is not a class or array type, it will be zero-initialised.

Our c is initialised from this temporary, so it takes on the value 0. This effectively results in ptr being a zero-length, null-terminated C string.

A declaration like char c; does not satisfy this criterion!

Upvotes: 4

Related Questions