473,387 Members | 1,374 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

C# pitfall: local variables returned must be initialized to somevalue first

Beware this newbie trap:

private bool myFunction (Myenum X)
{
bool local_bool; //this will not compile; you need to do this first:
bool local_bool = true;

switch (X) {

case 1:
local_bool = true;
break;

case 2:
local_bool=false;
break;
}

return local_bool;

}

This will not compile. You need to add a 'temporary' actual value for
it to compile, see the comment // above

RL

Hahahaha! You fed the troll! Eh, paranoid Marc and Goran? Koo-koo!
Sep 8 '08 #1
10 3060
It won't compile because the compiler thinks that there is no guarantee that
one of the cases in the switch will be executed. If you add a default that
sets some value for local_bool, it will compile without the initializer on
the definition.
Also, if _all_ the possible values of an enum are covered by a switch
statement, it will compile. The compiler wants it to be _certain_ that that
variable is initialized before it's used.
Sep 8 '08 #2
raylopez99 wrote:

<snipped>
Only a newbie would post something like that.
Beware this newbie trap:
Hahahaha! You fed the troll! Eh, paranoid Marc and Goran? Koo-koo!
What is wrong with you? You seem to be two years old. Is it because of
that Spanish blood in you that you act like a hot head pistol? Or could
it be that you hang out in the cesspool Linux.Advocacy?
Sep 8 '08 #3
On Mon, 8 Sep 2008 05:15:50 -0700 (PDT), raylopez99
<ra********@yahoo.comwrote:
>Beware this newbie trap:

private bool myFunction (Myenum X)
{
bool local_bool; //this will not compile; you need to do this first:
bool local_bool = true;

switch (X) {

case 1:
local_bool = true;
break;

case 2:
local_bool=false;
break;
}

return local_bool;

}

This will not compile. You need to add a 'temporary' actual value for
it to compile, see the comment // above
What you describe as a 'temporary' value isn't temporary if the value
of Myenum X is not one or two. Leave the switch out and the method
body is...

bool local_bool;
return local_bool;

What value do you believe the method should return?

regards
A.G.
Sep 8 '08 #4
"Arthur Parker" <Ar**********@discussions.microsoft.comwrote in message
news:9D**********************************@microsof t.com...
Also, if _all_ the possible values of an enum are covered by a switch
statement, it will compile. The compiler wants it to be _certain_ that
that
variable is initialized before it's used.
Actually, no, it won't, because range of allowed values for any enum type is
exactly the same as for its underlying integer type - it just so happens
that some of enum values are named, and others have to be obtained by
casting a plain integer value to enum type. Consider:

enum FooBar { Foo, Bar }

void Baz(FooBar x)
{
int y;
switch (x)
{
case FooBar.Foo: y = 0; break;
case FooBar.Bar: y = 1; break;
}
Console.WriteLine(x); // use of unassigned local variable ...
}

// ... because the caller can always do this:
Bar((FooBar)123);
Sep 8 '08 #5
First, I strongly recommend you simply ignore RL...
Also, if _all_ the possible values of an enum are covered by a switch
statement, it will compile.
I doubt it would; first this would mean every possible value of the
underlying data type [such as int] (enum values are not validated) - and
second, it doesn't even do this for "bool" - so I doubt it does it for
enum.

I can't see anything in the rules for definite assignment that would
make it care about all possible values being covered.

Marc
Sep 8 '08 #6
On Sep 8, 9:10*am, "Pavel Minaev" <int...@gmail.comwrote:
"Arthur Parker" <ArthurPar...@discussions.microsoft.comwrote in message

news:9D**********************************@microsof t.com...
Also, if _all_ the possible values of an enum are covered by a switch
statement, it will compile. *The compiler wants it to be _certain_ that
that
variable is initialized before it's used.

Actually, no, it won't, because range of allowed values for any enum typeis
exactly the same as for its underlying integer type - it just so happens
that some of enum values are named, and others have to be obtained by
casting a plain integer value to enum type. Consider:

* * enum FooBar { Foo, Bar }

* * void Baz(FooBar x)
* * {
* * * * int y;
* * * * switch (x)
* * * * {
* * * * * * case FooBar.Foo: y = 0; break;
* * * * * * case FooBar.Bar: y = 1; break;
* * * * }
* * * * Console.WriteLine(x); // use of unassigned local variable...
* * }

* * // ... because the caller can always do this:
* * Bar((FooBar)123);
Pavel meant this, I think:
...
}
Console.WriteLine(y); // use of unassigned local variable
"y" ...
}
...
Sep 8 '08 #7
private bool MyFunction(MyEnum x)
{
switch (X)
{
case 1:
return true;

default:
return false;
}
}

Sep 8 '08 #8
On Sep 8, 6:06*am, Registered User <n4...@ix.netcom.comwrote:
>
What you describe as a 'temporary' value isn't temporary if the value
of Myenum X is not one or two. Leave the switch out and the method
body is...

* * * * bool local_bool;
* * * * return local_bool;

What value do you believe the method should return?
The one in the case statement.

Put another way: this would work:
//
private bool MyFunction(MyEnum x)
{
switch (X)
{
case 1:
return true;
default:
return false;
}
//

And so would this (I think, but I haven't tried it):

private bool myFunction (Myenum X)
{

bool local_bool = new bool(); //I think this will work and avoid
having to initialize the local_bool to something

switch (X) {
case 1:
local_bool = true;
break;
case 2:
local_bool=false;
break;
}

return local_bool;
}
So why doesn't my original post work? Oh well, there's an easy
workaround, which as I said in the OP is to add a fake value for
local_bool at the beginning. BTW the same thing used to happen in C++
for references--you had to 'initialize' references (&myRef = Object;)
to an actual instantiated object before anything with a reference
would compile. We've come a long way in C# since then, but vestiges
remain.

RL
Sep 8 '08 #9
On Mon, 8 Sep 2008 13:34:46 -0700 (PDT), raylopez99
<ra********@yahoo.comwrote:
>On Sep 8, 6:06*am, Registered User <n4...@ix.netcom.comwrote:
>>
What you describe as a 'temporary' value isn't temporary if the value
of Myenum X is not one or two. Leave the switch out and the method
body is...

* * * * bool local_bool;
* * * * return local_bool;

What value do you believe the method should return?

The one in the case statement.
There is no case statement in the snippet above or the method below.
private bool MyFunction(MyEnum x)
{
* * * * bool local_bool;
* * * * return local_bool;
}
What value do you expect the method to return?
>Put another way: this would work:
//
private bool MyFunction(MyEnum x)
{
switch (X)
{
case 1:
return true;
default:
return false;
}
//
Yes this works because the value to be returned is initialized before
the value is returned. Your original example contained a switch with
no default case. Change default : to case 2: and the code won't
compile.
>
And so would this (I think, but I haven't tried it):

private bool myFunction (Myenum X)
{

bool local_bool = new bool(); //I think this will work and avoid
having to initialize the local_bool to something
You think it will work? Do you not understand what the line
bool local_bool = new bool();
does? You are initializing a local variable while your supposed intent
is to avoid initializing a local variable.

- snip -
>
So why doesn't my original post work?
Because it is bad code. within the scope of your example the return
value may not be initialized.
>Oh well, there's an easy
workaround, which as I said in the OP is to add a fake value for
local_bool at the beginning.
Yep, that is some genius stuff alright. You must be the smartest guy
at your keyboard.

regards
A.G.
Sep 8 '08 #10
On Sep 8, 2:38*pm, Registered User <n4...@ix.netcom.comwrote:
Change default : to case 2: and the code won't
compile.
And why is that, Einstein?
bool local_bool = new bool(); //I think this will work and avoid
having to initialize the local_bool to something

You think it will work? Do you not understand what the line
* * * * bool local_bool = new bool();
does? You are initializing a local variable while your supposed intent
is to avoid initializing a local variable. *
No. You don't know the difference between stack and heap. We are
talking about stack (non-new) variables not heap. I mentioned it
because changing the variable from stack to heap works, and my
question (implicitly) is why it won't do the same for stack variables.
>
Yep, that is some genius stuff alright. You must be the smartest guy
at your keyboard.
At least I can qualify for that honor. You are the dumbest guy, at
your keyboard.

RL
Sep 9 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Tim Hill | last post by:
I'm just getting up to speed on Java, and have a question about local class behavior. Here's a mini-app to illustrate: interface Foo { void print(); } class LocalClassTest { public static...
4
by: Eric Baker | last post by:
With this little snippet, i get an inconsistency between the behavior of string and dictionary class variables: Python 2.2.3 (#42, May 30 2003, 18:12:08) on win32 Type "copyright", "credits" or...
2
by: Simon Harvey | last post by:
Hi everyone, I'm still abit confused about static methods accessing locally declared variables. For example public static bool executeNonQuery(){ SqlCommand cmd; SqlConnection con;
12
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline...
3
by: Jeremy | last post by:
I am relativly new to ASP.NET, and my question is this: Is it better to create a wrapper class that contains all the running settings for the application and then load that into the app state, or...
21
by: Sriram Rajagopalan | last post by:
Hi, Which of these two would be a better way of initializing the local variables? and why? 1) At the time of their declaration. Eg: void func()
55
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in...
23
by: Kira Yamato | last post by:
It is erroneous to think that const objects will have constant behaviors too. Consider the following snip of code: class Person { public: Person(); string get_name() const
9
by: raashid bhatt | last post by:
does having more variables increases the size of program.
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.