user6720691 user6720691 - 9 months ago 40
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){
printf("%d\n", x);
printf("before the loop, X had a value of %d", x);

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

Answer Source

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);