How to default-initialize local variables of built-in types in C++?

How do I default-initialize a local variable of primitive type in C++? For example if a have a typedef:

typedef unsigned char boolean;//that's Microsoft RPC runtime typedef

I'd like to change the following line:

boolean variable = 0; //initialize to some value to ensure reproduceable behavior retrieveValue( &variable ); // do actual job

into something that would automagically default-initialize the variable - I don't need to assign a specific value to it, but instead I only need it to be intialized to the same value each time the program runs - the same stuff as with a constructor initializer list where I can have:

struct Struct { int Value; Struct() : Value() {} };

and the Struct::Value will be default-initialized to the same value every time an instance is cinstructed, but I never write the actual value in the code.

How can I get the same behavior for local variables?

-------------Problems Reply------------

You can emulate that behaviour by the following:

boolean x = boolean();

or, more general,

T x = T();

This will default-initialize x if such a default-initialization exists. However, just writing T x will never do the trick for local variables, no matter what you do.

You can also use placement-new to invoke a “constructor”, even for POD:

T x;
new (&x) T();

Notice that this code produces undefined behaviour for non-POD types (in particular for types that have a non-trivial destructor). To make this code work with user-defined types, we first need to call the object’s destructor:

T x;
new (&x) T();

This syntax can also be used for PODs (guaranteed by §§5.2.4/12.4.15) so the above code can be used indiscriminately for any type.

int var = int();
string str = string();

...or whatever typename you want.

You could provide a wrapper that behaves as the underlying type through overloaded conversion operators.

#include <cassert>

template <class T>
class Type
T t;
Type(const T& t = T()): t(t) {}
operator T&() { return t; }
operator const T&() const { return t; }

int main()
Type<unsigned char> some_value;
assert(some_value == '');

This should be a rather OK usage for conversion operators.

Wrapping in the struct (Boolean) as in your example and accessing via a public member (Boolean::value). It may not be the most elegant solution (some cruft for small benefit), but it similar to what you already showed.

If I understand the original question, the poster is saying he wants variables of a given type to always have the same initial value, but he doesn't care what that value is, because he'll never look at it. Am I right?

If so, then my question for the poster is this: If you did not initialize the variables they would have random initial values... but you said you never look at initial values - so why does it matter if they're random?

I think the key question is - what are you trying to achieve here?

Category:c# Views:1 Time:2010-04-06

Related post

  • !ClrStack local variables - is it value type or reference type 2010-09-28

    How can I determine if the local variable is a value type or a reference type? 0:000> !CLRStack -a OS Thread Id: 0xf74 (0) Child-SP RetAddr Call Site 000000000023e9c0 000007fef6b32012 ConsoleApplication2.Program.Main(System.String[]) PARAMETERS: a

  • Default initialization of variables in action forms 2010-07-31

    i have made a from like : MyForm extend ActionForm{ list<Menu> MenuList=null; MyForm(){ super(); setMenuList(); //initialize menu list } } Menu object has string desciption and boolean variable for selected or not. In web page, i am iterating t

  • Auto generate constructor with default initialization of variables 2011-11-19

    This might be a super-lame lazy question. Is it possible to generate constructor in Eclipse like class A{ int a; String b; float c; /* Is it possible to auto-generate this*/ public A() { a = 0; b = ""; c = 0f; } } I am aware that default initializati

  • How to initialize empty variables from your own type in Scala? 2012-03-29

    My problem is understanding is the syntax of Scala. I come from a Java background. I am trying to make a variable of the same type as the class it is in. Example: class Exp { var exp1: Exp; } I am getting this error: Driver.scala:4: error: class Exp

  • Why Java initializing only class variables by default but not local variables? 2014-10-26

    I am learning linkedlist in Java and I have three files, and When I am doing this, I got a question why should I initialize a local variable which is declared in method and but not class variable which is declared in cl

  • Should Local Variable Initialisation Be Mandatory? 2008-09-26

    The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still see them and occasionally hear performance implications given as their just

  • Uninitialized class members in Java do not issue any compiler errors. local variables however do. Why? 2011-12-15

    Consider the following code snippet in Java. its not going to be compiled. package temppkg; final public class Main { private String x; private int y; private void show() { String z; int a; System.out.println(x.toString()); // Causes a NullPointerExc

  • Why compile error "Use of unassigned local variable"? 2012-02-10

    My code is the following int tmpCnt; if (name == "Dude") tmpCnt++; Why is there an error Use of unassigned local variable tmpCnt? I know I didn't explicitly initialize it but due to Default Value Table a value type is initialized with 0 anyways. The

  • what can you initialize global variables to in c++ 2011-05-01

    Can you intialize global variables in c++, and if possible, what values are allowed? --------------Solutions------------- Yes, of course you can initialize globals. For built-in types, you can use any value you could use for assignment (and you can a

  • Injecting a local variable to a binding 2012-03-12

    I am trying to set a local variable to an existing binding def foo_callback lambda { |name| p name } end b = foo_callback.binding The binding doesn't have any local variables to begin with: b.eval("local_variables") # => [] Let us set a primitive

  • Can I programatically get hold of the Autos/local variables that is shown when debugging? 2010-03-09

    Im trying to build an error-logger that loggs running values that is active in the function that caused the error. (just for fun so its not a critical problem) When going in break-mode and looking at the locals-tab and autos-tab you can see all activ

  • The final local variable cannot be assigned 2012-04-15

    I have an array of seats, and the array has two strings(selected and empty). On mouse click, I want to traverse the array and find the selected seat. When I press the button it says: "The final local variable seatno cannot be assigned, since it is de

  • Do objects of built-in types have special static initialisation order precedence? 2012-01-05

    I'd have expected the following code to yield a segmentation fault (or otherwise UB): struct T { T(); }; T t; char const* str = "Test string"; T::T() { std::cout << str; // zero-initialised, only! } int main() {} That's because t is initialised

  • Do g++ thread-local variables follow default initialization rules? 2010-07-02

    Using g++ to declare function-static thread-local storage: void f() { static __thread somePodStruct thing; ... } can I assume that thing will get zero-initialized? --------------Solutions------------- According to the GCC documentation:

  • Initialization of instance fields vs. local variables 2009-10-09

    I have always been wondering about why in the following example it is OK to not initialize the instance field (relying that it will have its default value) and accessing it, while local variables apparently must be initialized, even if I initialize i

  • C# Local Variables Initialization - Beginner's Question 2010-11-15

    I am reading MCTS Self Paced Training Kit (70-536) Edition 2 and in the 1st chapter we have the following. How to Declare a Value Type Variable To use a type, you must first declare a symbol as an instance of that type. Value types have an implicit c

  • Initialize implicitly typed local variable to IList 2011-04-20

    I understand that implicitly-typed local variables must be initialized. I know that result will be an IList so could I somehow say that var result will be an IList? var result; //initialize to something if( x < 0) { result = (from s in context.som

  • How to initialize a local variable in its declaration in Eiffel? 2011-11-10

    I tried to do this: local condition: BOOLEAN condition := true do And something like this: local condition: BOOLEAN := true do Obviously neither work, but I need to initialize a variable inside the declaration because I don't want the variable to re-

  • How to prevent default initialization of a const variable with a class type 2011-11-18

    I have a custom class that I want to behave like a built-in type. However I have noticed that you can initialise a const variable of that class without providing an initial value. My class currently has an empty default constructor. Here is a compari

Copyright (C), All Rights Reserved.

processed in 0.155 (s). 11 q(s)