Why is initialization of a new variable by itself valid?

Consider some code:

#include <iostream> int main() { using std::cout; int a=3; cout << "a="<<a<<"\n"; { int a=a; cout << "new a = " << a << "\n"; a=5; cout << "a = " << a << "\n"; } cout << "old a = " << a << "\n"; }

I'd expect it to print

a=3 new a = 3 changed a = 5 old a = 3

But what I get actually appears to say new a = 0 in the second line. I thought that it would work like initialization list in a class' constructor, where one can write like

C::C(int a) : a(a) {}

But for some reason this is different. First, removing the outer code completely doesn't result in a compilation error. So I assume that int a=a; is valid. Turning on all the compiler warnings leads to this:

test.cpp: In function ‘int main()’: test.cpp:10:15: warning: ‘a’ is used uninitialized in this function int a=a;

So my question now: why is this syntax valid at all? Why doesn't the compiler say something like "undefined variable a"?

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

It's syntactically valid, since the variable's point of declaration comes before its initialiser, and the name is available anywhere after that point. This allows less dodgy initialisations like

void *p = &p;

which legitimately uses the name (but not the value) of the variable being initialised.

It's behaviourally invalid, since using the value of an uninitialised object gives undefined behaviour. That's not an error that requires diagnosis (since, in general, it can be difficult or impossible to analyse the program flow to see whether an object has been initialised), but as you note, many compilers will give a warning for straightforward cases like this.

Category:c# Views:0 Time:2015-01-26

Related post

  • Do I have to initialize simple class member variables? 2010-06-16

    Quick beginner's question: Do I have to initialize simple class member variables, or are they guaranteed to get assigned their default values in any case? Example: class Foo { int i; // is i==0 or do I need the following line for that? Foo() : i(0) {

  • Why is initialization of integer member variable (which is not const static) not allowed in C++? 2010-12-01

    My C++ compiler complains when i try to initialize a int member variable in class definition. It tells "only static const integral data members can be initialized within a class". Can you please explain the rationale behind this restriction (if possi

  • How do I initialize static constant member variables in a subclass? 2011-05-09

    I'm trying to make a template which can make a few different types of classes that differ mainly in the name of things, i.e. a resistor should output "Resistance: 4 ohm" where a capacitor would output "Capacitance: 4 farad" in the same function call,

  • Dynamic initialization phase of static variables 2011-06-16

    The standard specifically states that dynamic initialization of static duration variables (namespace scope and class static members) does not have to occur before main is executed: "It is implementation-defined whether or not the dynamic initializati

  • EXC_BAD_ACCESS signal when trying to initialize __m128 class member variable 2011-06-23

    I'm using Apple GCC 4.2.1 and I've stumbled upon a strange problem with the following code... I always get EXC_BAD_ACCESS exception when trying to initialize __m128 class member variable. Unfortunately the following simplified code works in a test ap

  • How can I initialize normal array member variable in initializer list? 2011-09-22

    I would like to do the following: class MyClass { public: MyClass() : arr({1,2,3,4,5,6,7,8}) {} private: uint32_t arr[8]; }; but it doesn't work (compiler: expected primary expression before '}' token.). I've looked at other SO questions and people w

  • Uniform initialization with {} reporting unused variable 2012-03-18

    Compiling this code with g++ 4.7.0 (-Wall -Wextra -Werror -Wconversion -std=c++11): #include <iostream> // std::cout, std::endl #include <string> // std::string #include <utility> // std::move void out(std::string const &message

  • Is this list-initialization of an array of unknown size valid in C++0x? 2010-04-10

    Is this list-initialization of an array of unknown size valid in C++0x? int main() { int x[]{0, 1,2,3,4}; return x[0]; } I believe it is valid, but would appreciate some confirmation. If anyone could quote from the C++0x-FCD to support their case, it

  • Right way to conditionally initialize a C++ member variable? 2009-06-18

    I'm sure this is a really simple question. The following code shows what I'm trying to do: class MemberClass { public: MemberClass(int abc){ } }; class MyClass { public: MemberClass m_class; MyClass(int xyz) { if(xyz == 42) m_class = MemberClass(12);

  • Visual studio 2005: is there a compiler option to initialize all stack-based variables to zero? 2009-11-04

    This question HAS had to be asked before, so it kills me to ask it again, but I can't find it for all of my google and searching stackoverflow. I'm porting a bunch of linux code to windows, and a good chunk of it makes the assumption that everything

  • Initialize a NSString member variable inside the view controller 2010-01-21

    I have a NSString member variable declared in the header file of the view controller: @interface MyApprViewController : UIViewController { NSString *var; ... } @property (retain) NSString *var; ... -(IBAction)buttonPressed: (id)sender; Inside the imp

  • Initialization of function static variables 2010-02-03

    I have one static variable declared inside a function, which is not initialized to zero explicitly. Are all uninitialized static variables inside functions set to zero by default, just as static variables at the global (file) level are? -------------

  • Initialization order of static variables 2010-08-28

    I'm trying to confirm whether static variable initialization in Objective-C works the same as it does for C++. Specifically do static variables have the possibility of being instantiated/created before main() is called? --------------Solutions-------

  • initialization of the static variables 2010-10-09

    I've just read that if I want to be sure about the initialization order it will be better to use some function which will turn global variable into local(but still static), my question, do I need to keep some identifier which tells me that my static

  • Is there a way to make a C++ struct value-initialize all POD member variables? 2010-10-14

    Suppose I have a C++ struct that has both POD and non-POD member variables: struct Struct { std::string String; int Int; }; and in order for my program to produce reproduceable behavior I want to have all member variables initialized at construction.

  • How can I automatically initialize all the scalar variables in Perl? 2010-11-03

    Perl automatically initializes variables to undef by default. Is there a way to override this default behavior and tell the Perl interpreter to initialize variables to zero (or some other fixed value)? --------------Solutions------------- The recomme

  • Initialization of static class variable inside the main 2011-01-15

    I have a static variable in the class. I am Initializing that in the global scope, its works fine. But When I try to Initialize in the main linker throws an error. Why it so. class Myclass{ static int iCount; } ; int main(){ int Myclass::iCount=1; }

  • 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

  • Initialization order of static variables in Flex causing bug 2011-05-10

    I've got a component written for my app by a third party developer and am trying to integrate it, but I've found a bug that seems like it's either a compiler bug, or there's something with how Flex and static variables work that I wasn't aware of. Ba

Copyright (C) dskims.com, All Rights Reserved.

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