Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c++ - int var = 1; void main() { int i = i; }

This is an interview question that I had:

int var = 1;
void main()
{
    int i = i;
}

What is the value of i after assignment? It is really compiler dependent or is it just undefined? My g++ on cygwin seems to give me 0 all the time.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i has an indeterminate value because it is not initialized. So not only is it compiler dependent but it is dependent on whatever happens to be in that memory location. Variables in local scope are not initialized in C++.

I assume instead of int var = 1; at the top you meant int i = 1;.

The local scope i will still be used because the point of declaration for a variable is immediately after its declarator and before its initializer.

More specifically, Section 3.3.1-1 of the C++03 standard:

The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any), except as noted below. [Example:

int x = 12;
{ int x = x; }

Here the second x is initialized with its own (indeterminate) value. ]


On a side note I don't think this is a very good interview question because it is related to knowing some obscure fact about the language which doesn't say anything about your coding experience.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...