tags:

views:

122

answers:

4

Basically I want to create an int xfor every time a condition is met so something like...

while(CONDITION){
    if(int x = 100){
       //create a new int
       //refrence newly created variable
      }
   }

I then want to run through the loop again but testing newly created variable instead of x. Hopefully this is clear enough!

+2  A: 

There is no notion of "creating an int" in C language. You can assign a new value to an existing int if you want:

int x, newx;
while(CONDITION){
   if(x == 100){
      newx = x;
   }
}
Pablo Santa Cruz
+1 OMG, it seems you understood the question. I could not!
karlphillip
+2  A: 

In the C99 snippet below

for (int i = 0; i < 4; i++) {
    int x;
    x = i * 2;
}

the x is a brand new x every time through the loop.
During the time the program runs that snippet, there will be 4 different xs.

pmg
A: 

Your question is hard to understand, but it sounds almost like you want a for loop. E.g.

for (int x = 100; CONDITION; /* do something to x here */) {
  /* use x */
}

This will start x at 100, and continue looping while CONDITION is true. Depending on what you replace /* do something to x here */ with, the value of x within the loop will change each time. For a concrete example:

for (int x = 100; x < 200; x = x + 1) {
  printf("%d", x);
}

will print all numbers between 100 and 199 (inclusive). Note that x = x + 1 can also be written ++x or x++; I wrote it longhand for clarity, since you seem to be new to C.

The above assumes you have a C99 compiler. If your complier supports only C89, you will have to declare x at the beginning of the function and replace int x = 100 with simply x = 100.

Tyler McHenry
A: 

Your question isn't at all clear, but I think recursion may help you.

void do_it(void) {
    if (CONDITION) {
        int X = something_having_to_do_with_condtion(CONDITION); // the code you had
                                                     // for initializing X made no sense
        do_it(void); // recursive call

        process_x(X);
    }
}

You could do similar things with other dynamic allocation but the overhead is probably greater than that of recursion.

nategoose