top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: Is it possible to declare to two variables in one for loop?

+1 vote
459 views

something like

for (i=0,j=7;i<j;++i,--j)
posted Jan 8, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Yes, it can be done. "for" loop has three sections namely initialization, condition, increment/ decrement section.
Initialization and increment / decrement section may have multiple variables.

answer Jan 9, 2015 by Neeraj Mishra
0 votes

Yes definitely it is possible to declare one, or two, or three variable inside a for loop.
take your example as an example:

for (i = 0, j = 1, k = 4; some_condition as per your need; operation (increment/decrement, multiplication/division));
answer Jan 9, 2015 by Arshad Khan
Similar Questions
0 votes

Which is the best practice for variable declaration within the function ? Or is it vary from one language to other one ?

+1 vote

Check the following C example, why is one loop so much slower than two loops?

Suppose we have to add some values to array a1 and c1 of b1 and d1 respectively then there is big time difference in execution of both code..

const int n=100000;
for(int j=0;j<n;j++){
    a1[j] += b1[j];
    c1[j] += d1[j];
}

This loop is executed 10,000 times via another outer for loop. to speed it up, I changed the code to:

for(int j=0;j<n;j++){
    a1[j] += b1[j];
}
for(int j=0;j<n;j++){
    c1[j] += d1[j];
}

I don't think there should be any execution time difference but it is showing.

+5 votes

You can find three principal uses for the static. This is a good way how to start your answer to this question. Let’s look at the three principal uses:

  1. Firstly, when you declare inside of a function: This retains the value between function calls

  2. Secondly, when it is declared for the function name: By default function is extern..therefore it will be visible out of different files if the function declaration is set as static..it will be invisible for outer files

  3. And lastly, static for global parameters: By default you can use global variables from outside files When it’s static global..this variable will be limited to within the file.

is this right ?

...