Thread: declaring variables inside loops

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    182

    declaring variables inside loops

    Ok so, I know that if you declare a variable inside an if statement, then the variable will exist only inside the if block. But what about in loops? If I do something like:
    Code:
    for(whatever;bla;etc.) {
        int x;
        bla bla bla...;
    }
    Is it efficient? I thought that maybe it could declare multiple times the variable and be inefficient actually, but I'm not sure.

    Thing is that I want to declare a variable that will only be used inside the for. I have seen the declaration inside the for parentheses:
    Code:
    for(int x; bla; bla)
    But the compiler gives me a warning, something about not C99.

    Thanks.

  2. #2
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Yeah, you can only declare them like that in C when compiling as C99. I think most compilers are set to C98 mode by default. (they are different C standards btw)

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    182
    well is the first way (the one that the declaration is inside the for loop) efficient or does it make a new variable every time the loop turns?

  4. #4
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    I don't know if the compiler would optimise it or not, but if its setting a new one each time then it would be less efficient. You could always time it and see.

  5. #5
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    well is the first way (the one that the declaration is inside the for loop) efficient or does it make a new variable every time the loop turns?
    No, it is not reallocated for each loop, the only difference for the compiler is to reduce
    the scope of the variable.

  6. #6
    Registered User
    Join Date
    Jan 2008
    Posts
    182
    cool thanks

  7. #7
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Is it efficient? I thought that maybe it could declare multiple times the variable and be inefficient actually, but I'm not sure.
    It should be as efficient as it would be declaring it at the top of the function. It only declares it once, when it enters the scope (the scope being what's between the left and right braces), and depending on the compiler, may actually delete the variable, once it exits the scope (though it may wait until the end of the function).

    >Thing is that I want to declare a variable that will only be used inside the for.
    For gcc, you can add -std=c99 to your compiler options. That would include Dev-C++ and code::blocks IDEs.

  8. #8
    Registered User
    Join Date
    Jan 2008
    Posts
    182
    yes, I use MinGW... what do I do, just write -std=c99 as argument? And, what's better? C99 or gcc's default?

  9. #9
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Unless C handles loops significantly differently than C++, the following should be true for this code:
    Code:
    int main()
    {
    	for ( int i = 0; i < 5; ++i )
    	{
    		double d;
    	}
    
    	return 0;
    }
    i is created once, and d is created 5 times.

  10. #10
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Someone (I think it was Bubba) told me that the compiler would likely optimise it so that the variable declaration is done out of the loop. It also wouldent need to be switched in and out of scope (as theres only one scope for it here). I dont know if there would be any overhead for dealing with different scopes?

  11. #11
    Registered User
    Join Date
    Jan 2008
    Posts
    182
    hmmm.. now I'm not sure. I thought swoopy said that d would be allocated only one time, that the scope would be the only difference if it is declared inside the loop. Now, in C89 I can't declare i like that, I have to set my compiler to C99.

    I'll leave the declarations outside the loop just in case.

  12. #12
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    If you're not convinced of how the compiler handle those variables, this is quite easy:
    write two simple functions using the two cases (declaration outside and inside a loop)
    then compare the disassembled code, you'll see that the instructions generated
    are the same, you don't even have to understand what it does.

  13. #13
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >yes, I use MinGW... what do I do, just write -std=c99 as argument?
    Yes. And of course there's -std=c89 for the C89 standard.
    >And, what's better? C99 or gcc's default?
    If you want to write portable code (works on any system) it's best to use the c89 switch (and also turn up the warning level (-Wall). gcc's default is best if you want to use any of gcc's extensions and don't care as much about portability. C99 is the latest standard. Use it if you need some of it's features (like specific sizes for int's or complex math, for example).

    I think gcc's default allows variable declarations anywhere.
    Last edited by swoopy; 04-29-2008 at 07:13 PM.

  14. #14
    Registered User
    Join Date
    Jan 2008
    Posts
    182
    Code:
    #include <stdio.h>
    
    int main(void)
    {
    	int x;
    	int number;
    	
    	for(x=0; x<100; x++) {
    		number = 0;
    		number += 2;
    		printf("Number = %d\n",number);
    	}
    	
    	return 0;
    }
    Same assembler code as:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
    	int x;
    	
    	for(x=0; x<100; x++) {
    		int number = 0;
    		number += 2;
    		printf("Number = %d\n",number);
    	}
    	
    	return 0;
    }
    Code:
    	.file	"test1.c"
    	.def	___main;	.scl	2;	.type	32;	.endef
    	.section .rdata,"dr"
    LC0:
    	.ascii "Number = %d\12\0"
    	.text
    .globl _main
    	.def	_main;	.scl	2;	.type	32;	.endef
    _main:
    	pushl	%ebp
    	movl	%esp, %ebp
    	subl	$24, %esp
    	andl	$-16, %esp
    	movl	$0, %eax
    	addl	$15, %eax
    	addl	$15, %eax
    	shrl	$4, %eax
    	sall	$4, %eax
    	movl	%eax, -12(%ebp)
    	movl	-12(%ebp), %eax
    	call	__alloca
    	call	___main
    	movl	$0, -4(%ebp)
    L2:
    	cmpl	$99, -4(%ebp)
    	jg	L3
    	movl	$0, -8(%ebp)
    	leal	-8(%ebp), %eax
    	addl	$2, (%eax)
    	movl	-8(%ebp), %eax
    	movl	%eax, 4(%esp)
    	movl	$LC0, (%esp)
    	call	_printf
    	leal	-4(%ebp), %eax
    	incl	(%eax)
    	jmp	L2
    L3:
    	movl	$0, %eax
    	leave
    	ret
    	.def	_printf;	.scl	2;	.type	32;	.endef
    The only thing that changes is the file name.

    And the only problem I have is that if you declare an initialized variable inside the for loop, it will be initialized in every single loop. So... its not good in some cases.

  15. #15
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Unless the loop is iterating millions (or maybe even billions) of times, it probably won't make much of a speed difference either way; but to be sure the loop is optimal, I'd declare variables before the loop. Some compiler optimizers might not be as good as others, and in debug mode it won't optimize anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 15
    Last Post: 09-30-2008, 02:12 AM
  2. Declaring SDL_Rect variables in a class?
    By pwnz32 in forum C++ Programming
    Replies: 10
    Last Post: 07-27-2008, 07:12 PM
  3. Declaring an variable number of variables
    By Decrypt in forum C++ Programming
    Replies: 8
    Last Post: 02-27-2005, 04:46 PM
  4. simple question about variables and loops
    By InvariantLoop in forum C Programming
    Replies: 2
    Last Post: 01-26-2005, 09:47 AM
  5. static variables inside of a class.. possible?
    By revelation437 in forum C++ Programming
    Replies: 2
    Last Post: 03-13-2003, 05:21 PM