473,545 Members | 2,073 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2660
In article <05************ *************** *******@f10g200 0hsf.googlegrou ps.com>,
<po************ *@gmail.comwrot e:
>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.c omwrites:
>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**********@a ioe.org>, santosh <sa*********@gm ail.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

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

Similar topics

83
6423
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 C. It can cause very ugly errors,like this: epsilon=0 S=0 while epsilon<10: S=S+epsilon
5
3316
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
2654
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 before the variable is used? I'm trying to get an idea of whether the .NET compilers for VB.NET and C# will move all variable declaration to the...
8
3128
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
2377
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 loop wasn't good practice, something like: for(int i=0; i<size-1; ++i){ int aux = array; array=array; array=aux; }
21
2804
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 of x is: %d\n", x);
28
4284
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
2186
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 for help! #include <stdio.h> #include <stdlib.h> #define __buff(s, c) s_c
10
4119
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 ((int i = getint()) != 0) {
0
7470
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7659
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7811
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
5975
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5334
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4949
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1887
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1019
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
709
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.