user6720691 user6720691 - 1 month ago 10
C Question

How to get value of a variable before a loop after loop is executed?

I would like to know if there is a way to get the value of an integer variable before it entered the loop, after the loop has been executed.

For example:

#include <stdio.h>
int main(){
int x;

x = 1;
printf("%d\n", x);

while(x < 2000){
x++;
printf("%d\n", x);
}
printf("before the loop, X had a value of %d", x);
}


Is there a way to have the final
printf()
print the value of
x
which the
x
was holding before entering the
while()
loop? Or is the only way to create a copy of
x
using another variable before the loop?

AnT AnT
Answer

In the abstract context you would typically have two options:

  1. Store the original value beforehand, i.e. create a copy.
  2. Use the new value as a starting point to "revert" all modifications and thus arrive at the original value.

In general case there are trade-offs associated with each approach.

Applied to your specific simple example, these two approaches involve either storing the copy of the variable before the loop or "undoing" the changes done by the loop (by using your intimate knowledge of this loop's semantics). The latter in this case boils down to

printf("before the loop, X had a value of %d", x - 1999);