Menu

01 January 2007

Scope Rule of for loop in C++










Q. what is the result of this program with and without static?

A.
variable i is defined at two place. So confusion arise as there are two i++, which i is incrementing at both place. Let name them as “frist i++” that is round bracket and “second i++” that is in curly bracket

Now if you see the diagram below then you will be at stage of giving answer.

The above code is equivalent to














Important thing is above diagram is curly brackets {} that tells the scope provided by a for loop. see outside i is initialized with zero, that has scope in main function. Statement i<5>

Now see curly brackets, in that i is defined as static means i will be created and assigned once that is if we some how managed to come again this place by goto statement or by using loop or calling the function again the statement will not execute moreover this will preserve its value also. statements like “second i++” an cout<<i will print value 5

so output will be

101

102

103

104

105

5

if static keyword is omitted then i inside curly bracket will be created again and again whenever loop runs

so the output will be

101

101

101

101

101

5

Q. now based on abode discussion i am modifying the code, don’t see answer now write your result first then and match it with my answer,






A.

see the difference , first field is empty and one more cout is present which has scope in main. so first i++ and cout<

the flowchart will be















so the result will be

101

1

102

2

103

3

104

4

105

5

5

readers can easily justify the output without static in this case

hey if you are on orkut why do not you join my "c++ help for all " community

1 comment:

Narendra Sisodiya said...

Hi, This is applicable to TC compiler,,
according to new C++ standards ,, it is not applicable , as variable inside the loop is local to that loop only and not visible outside