[英]C: How can I alter which register a variable writes to?
C newbie here, wondering if anyone can point me in the direction of some reading material to solve this problem. 在这里,是C新手,想知道是否有人可以指出一些阅读材料的方向来解决这个问题。 I have 2 registers and a variable: 我有2个寄存器和一个变量:
Register->Foo;
Register->Bar;
myVar;
myVar
is the output of a math function, and the result gets written repeatedly to Register->Foo
for many cycles, then when a button is pressed, myVar
gets written repeatedly to Register->Bar
for many cycles. myVar
是数学函数的输出,并且在许多周期内将结果重复写入Register->Foo
,然后按下一个按钮,则将myVar
在多个周期内重复写入Register->Bar
。
Currently, I'm doing a check every cycle, like so: 目前,我正在每个周期进行检查,如下所示:
if button not pressed:
write myVar to Register->Foo
else
write myVar to Register->Bar
But I only really need to do a check whenever the button is pressed, not every instruction cycle. 但是我真的只需要在按下按钮时进行检查,而不必在每个指令周期中进行检查。 How can I change where myVar points to only on a button press, and have that setting stick for all cycles until the button is pressed again? 如何更改myVar仅在按按钮时指向的位置,并在所有循环中保持该设置不变,直到再次按下按钮? Is something like this possible? 这样的事情可能吗?
OutputRegister = myVar // have this run all the time inside a loop
// somewhere else
OutputRegister = Register->Foo or Register->Bar
// depending on button
// What data structure or method can I use to make this!
You use an extra variable, eg is_assigned
. 您使用一个额外的变量,例如is_assigned
。 When the button is pressed it's set to zero (meaning "false"), then you change the condition and assignments like this: 当按下按钮时,将其设置为零(表示“ false”),然后按以下方式更改条件和分配:
if (button_not_pressed && !is_assigned)
{
if (button_not_pressed)
Register->Foo = myVar;
else
Register->Bar = myVar;
is_assigned = 1;
}
This means that when button_not_pressed
is true, and is_assigned
is false, then do the statements inside. 这意味着,当button_not_pressed
为true且is_assigned
为false时,则在其中执行语句。 As is_assigned
is then set to true, the next iteration the condition will be false. 然后将is_assigned
设置为true,则下一次迭代条件将为false。
You should keep a pointer to the correct location. 您应该保持指向正确位置的指针。 That way you can assign to it and change the destination on some other trigger. 这样,您可以分配给它并在其他触发器上更改目标。
For example: 例如:
int foo;
int bar;
int * dest;
void on_button_press() {
dest = &bar;
}
void on_button_release() {
dest = &foo;
}
void main() {
for (;;) {
// code
*dest = myVar;
// code
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.