James Hurley
James Hurley

Reputation: 762

Default Values C++11, compiler to compiler

Question 1:

How can you tell the default value of a variable? That is (if my vocabulary is wrong) the value of a variables before it is assigned?

Question 2:

How does this differ between compilers?

Question 3:

Is there a better way to default values?

Question 4:

And finally, are there other exceptions to this rule?

Example code:

bool foolean;
int fintoo;
double fooble;
char charafoo;

What would these be by default compiler to compiler?

Upvotes: 1

Views: 252

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361492

In all versions of C++, all the variables in your question will be zero-initialized (statically) if they're declared at namespace scope. In all other cases, they will have garbage values if left uninitialized.

Note that a garbage value is anything which is at the memory location where the variable is defined — it is just a pattern of 0s and 1s. Such values shouldn't be read by your program, else your code will invoke undefined behaviour.

In C++11, if you write these as local variables (or namespace variables):

bool foolean {};
int fintoo {};
double fooble {};
char charafoo {};

They're default-initialized which means zero in this case (as they are built-types).

Upvotes: 8

ach
ach

Reputation: 2373

If a variable is automatic (that is, a non-static variable local to a function, or a member thereof), there is no default. From pratical perspective, the variable is allocated on stack, and what's there on the stack (probably leftover from a previous function call) will become the value of the variable.

Also, some compilers add code to initialize the stack frame to a well-known value in debug mode. That lets you easily see that a variable hasn't been initialized while debugging.

If a variable is static (declared in namespace scope, or with the static keyword in a function), the default is zero.

Upvotes: 1

Related Questions