我想知道在执行循环之后是否有办法在进入循环之前获取整数变量的值。
例如:
#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);
}
在进入printf()
循环之前,有没有办法让最终x
打印x
所持while()
的值?或者是在循环之前使用另一个变量创建x
副本的唯一方法吗?
答案 0 :(得分:2)
在抽象上下文中,您通常有两个选项:
一般情况下,每种方法都存在权衡取舍。
应用于您的特定简单示例,这两种方法涉及在循环之前存储变量的副本,或者&#34;撤消&#34;循环所做的更改(通过使用您对此循环语义的深入了解)。在这种情况下,后者归结为
printf("before the loop, X had a value of %d", x - 1999);
答案 1 :(得分:1)
不,一旦修改了变量,就没有魔法方法来获取变量的初始(任何以前的状态)值。你必须自己创建(维护)一个副本。
答案 2 :(得分:0)
将循环前的旧值分配给另一个变量:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
<div class="row flex-container-1">
<div class="col-sm-4">
<div class="row">
<div class="col-sm-12">
<p>
US election: 2 days to go
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
Emotions run high in final days of the campaign
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
Person yells 'gun' ... Trump whisked away
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
US election: 2 days to go
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
Reality Check: Whoppers of the campaign
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
World of troubles for next US president
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
Pope warns against walls ahead of election
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
Rudy Giuliani changes his story on FBI
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
Trump knocks Mosul offensive
</p>
</div>
</div>
</div>
<div class="col-sm-8 flex-container-2">
<div class="row">
<div class="col-sm-12">
<p>
'It's gone mad outside'
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
'It's gone mad outside'
</p>
</div>
</div>
<div class="row margin-top-auto">
<div class="col-sm-12 beatthebottom">
<img class="img-responsive" src="http://placehold.it/350x150">
</div>
</div>
</div>
</div>
</div>
反之亦然,在循环中使用不同的变量并保持原始状态不变。
编译器无法为你做到这一点。