473,324 Members | 2,166 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,324 software developers and data experts.

declaration of variable in for loop

Hi there,

suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
}
When i see the address of K its same in all iterations.That means K is
only defined once at a time.
Is it because each for loop execution is considered as separte
block,its allocating in the same address?
or is it allocated memory only once?
Jan 31 '08 #1
12 2650
In article <05**********************************@f10g2000hsf. googlegroups.com>,
<po*************@gmail.comwrote:
>suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
}
>When i see the address of K its same in all iterations.That means K is
only defined once at a time.
Is it because each for loop execution is considered as separte
block,its allocating in the same address?
or is it allocated memory only once?
The answer is compiler dependant. C does not define when or where
memory allocation is made for automatic variables: it only
defines rules for when storage is meaningfully accessible, and
rules about which declaration of a name is the one denoted by
a mention of the name.

In some compilers the answer would be "neither of the above".
For example some compilers allocate automatic variables from
a heap, so the fact that the variable showed up with a particular
address in each iteration could just reflect the fact that no
unreleased heap allocations were made between iterations of the loop.

--
"Is there any thing whereof it may be said, See, this is new? It hath
been already of old time, which was before us." -- Ecclesiastes
Jan 31 '08 #2
DDD
On Jan 31, 2:25 pm, poornimampra...@gmail.com wrote:
Hi there,

suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}

}

When i see the address of K its same in all iterations.That means K is
only defined once at a time.
Is it because each for loop execution is considered as separte
block,its allocating in the same address?
or is it allocated memory only once?
because each for loop execution is considered as separte block. And
the memory address of K should be random.
Jan 31 '08 #3
po*************@gmail.com wrote:
Hi there,

suppose i have piece of code like
Include stdio.h here.
main()
int main(void) is better form.
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
You probably want:

printf("%d\t%p = %d\n", i, (void *)&k, k);

The 'p' format specifier expects a void * value and the type of the
value yielded by the address-of operator is "pointer to T" where T is
the type of it's operand. Also the '*' character in your format string
specifies that the following formatting operation be of the minimum
field width specified by the corresponding argument to '*'. In this
case it is the fourth printf() argument and thus, the final 'd'
specifier is left without an argument, invoking undefined behaviour.
}
}
When i see the address of K its same in all iterations.That means K is
only defined once at a time.
Is it because each for loop execution is considered as separte
block,its allocating in the same address?
or is it allocated memory only once?
This is implementation dependant. You cannot rely on the address of 'k'
being the same across iterations. However the compiler is very likely
to "optimise" in such cases and create and destroy 'k' only once for
the entire duration of the loop. But you cannot rely on such behaviour.

Jan 31 '08 #4
po*************@gmail.com wrote:
Hi there,

suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
}
When i see the address of K its same in all iterations.That means K is
only defined once at a time.
I don't understand what you mean by "once at a time"
Is it because each for loop execution is considered as separte
block,its allocating in the same address?
or is it allocated memory only once?
Who knows? More importantly, who cares?

1) The compiler's optimisation routines could have determined
that there was no need for k to be in the nested block and
moved it out
2) The management of memory at run time could (very likely would,
I suspect) mean that the same address was allocated each time
through the loop
3) There may be some other explanation

None of this behaviour is guaranteed by the standard, and it is
far from certain that it would be the same in another environment.

Why are you bothered about how the compiler has organised things?
Jan 31 '08 #5
On Jan 30, 10:25*pm, poornimampra...@gmail.com wrote:
Hi there,

suppose i have *piece of code like
main()
{
* * * * int i,j;
* * * * for(i=0;i<10;i++){
* * * * * * * * * * * * int k = i;
* * * * * * * * * * * * printf("%d * *%p = *%d\n",i,&k,k);
* * * * }

}

When i see the address of K its same in all iterations.That means K is
only defined once at a time.
Is it because each for loop execution is considered as separte
block,its allocating in the same address?
or is it allocated memory only once?
There is also this possibility: the address of k was produced only
because you asked for it with the & operator, and the existence of
this address doesn't prove that the value of k is actually ever stored
there.
Jan 31 '08 #6
po*************@gmail.com wrote:
Hi there,

suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
}
When i see the address of K its same in all iterations.That means K is
only defined once at a time.
For some compilers like lcc-win this is the case.
lcc-win allocates all local variables of the function, no
matter what scope, at the start of the function. The stack is not
modified within the function. This is done for obvious
performance reasons. Imagine that at the end of the
block the stack was adjusted, and at the start space
for the variable would be created. This would make for
at least 2 instructions per block iteration... not a good
idea.

Of course, the *scope* of the variable is ONLY within the
enclosing block. After the block is left, there is no way to access
that stack position within C, unless you take
the address of the local variable.

main()
{
int i,j, *pint;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
pint=&i;
}
*pint = 789; // Accessing illegal storage
}

This would work on lcc-win since the storage is still valid.
I would not do this since it is absolutely non portable.
Other compilers could implement other strategies.

For instance
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
}
The second "k" could be aliased by the compiler to the first one
and stored at the same memory location.
Is it because each for loop execution is considered as separte
block,its allocating in the same address?
or is it allocated memory only once?
For lcc-win it is the second.

--
jacob navia
jacob at jacob point remcomp point fr
logiciels/informatique
http://www.cs.virginia.edu/~lcc-win32
Jan 31 '08 #7
jacob navia wrote:

<snip>
main()
{
int i,j, *pint;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
pint=&i;
}
*pint = 789; // Accessing illegal storage
}

This would work on lcc-win since the storage is still valid.
I would not do this since it is absolutely non portable.
Other compilers could implement other strategies.
I hope as a QoI issue lcc-win issues a diagnostic for such uses?

<snip>

Jan 31 '08 #8
Mark L Pappin wrote:
jacob navia <ja***@nospam.comwrites:
>main()
{
int i,j, *pint;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
pint=&i;
}
*pint = 789; // Accessing illegal storage

What's illegal about it?

If the last statement inside the loop body had instead been
pint=&k;
then you might have a point.

mlp
Yes, I mistyped the name of the variable

Thanks
--
jacob navia
jacob at jacob point remcomp point fr
logiciels/informatique
http://www.cs.virginia.edu/~lcc-win32
Jan 31 '08 #9
In article <fn**********@aioe.org>, santosh <sa*********@gmail.comwrote:
>po*************@gmail.com wrote:
> printf("%d %p = *%d\n",i,&k,k);
>You probably want:
printf("%d\t%p = %d\n", i, (void *)&k, k);
>Also the '*' character in your format string
specifies that the following formatting operation be of the minimum
field width specified by the corresponding argument to '*'. In this
case it is the fourth printf() argument and thus, the final 'd'
specifier is left without an argument, invoking undefined behaviour.
That only applies if the * follows the %. Outside of a % specifier,
an * represents the literal character '*'.
--
"Beware of bugs in the above code; I have only proved it correct,
not tried it." -- Donald Knuth
Jan 31 '08 #10
poornimamprabhu wrote:
Hi there,

suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
}
When i see the address of K its same in all iterations.That means K is
only defined once at a time.
The compiler *is* allowed to place k in a different place each time, but,
why should it?

--
Army1987 (Replace "NOSPAM" with "email")
Jan 31 '08 #11
On Wed, 30 Jan 2008 22:47:11 -0800, DDD wrote:
On Jan 31, 2:25 pm, poornimampra...@gmail.com wrote:
>Hi there,

suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}

}

When i see the address of K its same in all iterations.That means K is
only defined once at a time.
Is it because each for loop execution is considered as separte
block,its allocating in the same address? or is it allocated memory
only once?

because each for loop execution is considered as separte block. And the
memory address of K should be random.
Why? There's no reason - as far as I can tell from the standard - to
expect that it _will_ have a random address, just that it _can_.

The optimizer may have found that each iteration does the equivalent of
"jump over N bytes, leaving that space to hold k", which is a waste of
time in this code - move it out of the loop and the loop will run faster,
the code can't tell the difference and the address won't change.

Jan 31 '08 #12
po*************@gmail.com writes:
suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
}
When i see the address of K its same in all iterations.That means K is
only defined once at a time.
Is it because each for loop execution is considered as separte
block,its allocating in the same address?
or is it allocated memory only once?
The name "k" refers to a distinct object for each iteration of the
loop. Conceptually, that object is created on entry to the block (the
"{") and destroyed on exit from the block (the "}"). Though there are
going to be 10 logically distinct objects, only one of them will exist
at any particular time. Similarly, if this code were inside a
function other than main, the variables "i" and "j" would exist only
while that function is executing. (The same thing applies to main,
but the concept is easier to understand if you consider a more
ordinary function.)

That's what the C language requires. It doesn't specify exactly what
a particular implementation must do to meet this requirement.

There are several ways to do this. Many, perhaps most,
implementations use a contiguous hardware stack for allocation of
local variables. In such an implementation, *either* shared space for
all instances of "k" is allocated on entry to the function, *or* space
for "k" is allocated and deallocated on each iteration of the loop.
In both cases, all instances of "k" are likely to have the same
address. This is just a consequence of the most natural way to
implement what the language requires; it is not itself required by the
language, and you should not depend on it.

For example, some implementations might allocate local storage on a
"heap", where successive allocations are not necessarily consecutive
in memory. In such an implementation, *if* "k" is allocated
separately each time the block is executed, then it could easily have
a different address on each iteration.

In any case, if you stick to what the language guarantees it's not
easy even to check whether all 10 "k"s have the same address. As soon
as "k" goes out of scope, even looking at its address without
dereferencing it invokes undefined behavior. You can, as you did,
display the address with printf and "%p", but the resulting text
string is implementation-defined, and it's not clear how much
information you can *portably* get out of it.

The best answer is just not to worry about it. Know that the compiler
will do what the standard requires it to do (unless it's buggy, which
does happen). If you're curious about how it does this, that's great;
curiosity is A Good Thing. But if your program actually depends on
the details, either you're doing something wrong or you're doing
something subtle and implementation-specific; in the latter rare case,
you'd better know exactly what you're doing.

(Somebody else in this thread already told you about the need to use
(void*)&k rather than just &k with the "%p" format. A couple of other
quibbles that aren't relevant to your question: use "int main(void)"
rather than "main()", and be sure you have a "#include <stdio.h>" at
the top of your program. You might be able to get away with "main()"
and without "#include <stdio.h>", but do it right anyway.)

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jan 31 '08 #13

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

Similar topics

83
by: Alexander Zatvornitskiy | last post by:
Hello All! I'am novice in python, and I find one very bad thing (from my point of view) in language. There is no keyword or syntax to declare variable, like 'var' in Pascal, or special syntax in...
5
by: Vasileios Zografos | last post by:
Ok, easy question. Not caring about the variable scope what is better (i.e. possibly in memory allocation etc) int someVar=0; for (int i=0;i<1000;i++) { ...
7
by: YGeek | last post by:
Is there any difference between declaring a variable at the top of a method versus in the code of the method? Is there a performance impact for either choice? What about if the method will return...
8
by: Alex Vinokur | last post by:
=========== Windows 2000 Intel C++ 8.0 =========== ------ foo.cpp ------ int main () { for (int i = 0; i < 10; i++); for (int i = 0; i < 10; i++);
39
by: Gaijinco | last post by:
I have always felt that you should only declared variables as needed, and implicitily it seems many authors to encourage it, but the other day a friend told me that declaring variables inside a...
21
by: Kannan | last post by:
Its been a while I have done pure C programming (I was coding in C++). Is the following function valid according to standard C? int main(int argc, char *argv) { int x; x = 9; printf("Value...
28
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
13
by: Carramba | last post by:
Hi! I have written some peace of code, but I wonder if it's legal for ansi-c I have no problem to compiling it, but since I'm inexperience and the output is not correct I have doubts. Thank you...
10
by: Zachary Turner | last post by:
Hello, This seems like an extremely basic question, and I'm a bit embarassed that I can't answer it myself. I just recently started using GCC and tried to type the following code: while...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.