Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Declaring int in the for loop

Tags:

c++

Haven't used C++ in a while. I've been depending on my Java compiler to do optimization.

What's is the most optimized way to do a for loop in C++? Or it is all the same now with moderm compilers? In the 'old days' there was a difference.

for (int i=1; i<=100; i++)

OR

int i;
for (i=1; i<=100; i++)

OR

int i = 1;
for ( ; i<=100; i++)

Is it the same in C?

EDIT: Okay, so the overwhelming consensus is to use the first case and let the complier optimize with it if it want to.

like image 719
Yada Avatar asked Feb 12 '10 22:02

Yada


People also ask

Should I declare variables in a loop?

It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope. What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs.

How do you declare an integer variable in C?

Declaring (Creating) Variablestype variableName = value; Where type is one of C types (such as int ), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign a value to the variable.

Can I declare a variable inside a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Can I declare variable in for loop in C?

In C and C++, there are currently two places you can declare a variable “in a for loop:” in the for statement itself, and in the statement it controls (loops). Consider: for (int i = 0; i < 42; ++i) {


2 Answers

The difference is scope.

for(int i = 1; i <= 100; ++i)

is generally preferable because then the scope of i is restricted to the for loop. If you declare it before the for loop, then it continues to exist after the for loop has finished and could clash with other variables. If you're only using it in the for loop, there's no reason to let it exist longer than that.

like image 196
Jonathan M Davis Avatar answered Oct 27 '22 04:10

Jonathan M Davis


Let's say the original poster had a loop they really wanted optimized - every instruction counted. How can we figure out - empirically - the answer to his question?

gcc at least has a useful, if uncommonly used switch, '-S'. It dumps the assembly code version of the .c file and can be used to answer questions like the OP poses. I wrote a simple program:

int main( )
{
    int sum = 0;

    for(int i=1;i<=10;++i)
    {
        sum = sum + i;
    }
    return sum;
}

And ran: gcc -O0 -std=c99 -S main.c, creating the assembly version of the main program. Here's the contents of main.s (with some of the fluff removed):

    movl    $0, -8(%rbp)
    movl    $1, -4(%rbp)
    jmp     .L2
.L3:
    movl    -4(%rbp), %eax
    addl    %eax, -8(%rbp)
    addl    $1, -4(%rbp)
.L2:
    cmpl    $10, -4(%rbp)
    jle     .L3

You don't need to be an assembly expert to figure out what's going on. movl moves values, addl adds things, cmpl compares and jle stands for 'jump if less than', $ is for constants. It's loading 0 into something - that must be 'sum', 1 into something else - ah, 'i'! A jump to L2 where we do the compare to 10, jump to L3 to do the add. Fall through to L2 for the compare again. Neat! A for loop.

Change the program to:

int main( )
{
    int sum = 0;
    int i=1;
    for( ;i<=10;++i)
    {
        sum = sum + i;
    }
    return sum;
}

Rerun gcc and the resultant assembly will be very similar. There's some stuff going on with recording line numbers, so they won't be identical, but the assembly ends up being the same. Same result with the last case. So, even without optimization, the code's just about the same.

For fun, rerun gcc with '-O3' instead of '-O0' to enable optimization and look at the .s file.

main:
movl    $55, %eax
ret

gcc not only figured out we were doing a for loop, but also realized it was to be run a constant number of times did the loop for us at compile time, chucked out 'i' and 'sum' and hard coded the answer - 55! That's FAST - albeit a bit contrived.

Moral of the story? Spend your time on ensuring your code is clean and well designed. Code for readability and maintainability. The guys that live on mountain dew and cheetos are way smarter than us and have taken care of most of these simple optimization problems for us. Have fun!

like image 36
Jesse K Avatar answered Oct 27 '22 03:10

Jesse K