在多次调用时将值存储在函数中 [英] Storing values in functions while calling multiple times

查看:127
本文介绍了在多次调用时将值存储在函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2 / *怀疑c程序,如何在函数中存储值,如果我调用函数变量被初始化并且先前的值被删除,那么如何在函数中存储值* /



2/* doubt regarding c program, how to store values in a function,if i call a function the variables are initialized and previous values are deleted so how can i store values in functions*/

#include <avr io.h="">
#include <util delay.h="">
#include "buzzer.h"

void ReachDestinationAvoidingNode(unsigned char Xd,unsigned char Yd,unsigned char Xn,unsigned char Yn)
{

}


//Do not make changes in main function

int main(void)
{
       ReachDestinationAvoidingNode(5,'D',6,'D');
       buzzer_on();
       _delay_ms(500);
       buzzer_off();
       ReachDestinationAvoidingNode(2,'F',2,'D');
       buzzer_on();
       _delay_ms(500);
       buzzer_off();
       ReachDestinationAvoidingNode(2,'A',2,'C');
       buzzer_on();

}





现在当ReachDestinationAvoidingNode(5,'D',6,'D')运行时被称为5,D值应该存储,并且当ReachDestinationAvoidingNode(2,'F',2,'D')调用5,D值时应该再次使用。该怎么做,

而不会打扰主码



我尝试过:



i尝试在ReachDestinationAvoidingNode()函数中存储变量并存储值但是当再次调用该函数时,变量被初始化并且值被删除;



now when the ReachDestinationAvoidingNode(5,'D',6,'D') function is called the 5,D values should be stored and again when the ReachDestinationAvoidingNode(2,'F',2,'D') called the 5,D values should be used. how to do that,
without disturbing main code

What I have tried:

i have tried taking variables in ReachDestinationAvoidingNode() functions and store values but when the function is called again the variables are initialized and the value gets deleted;

推荐答案

如果你只需要存储最后一个调用的参数,那么你可以使用本地静态变量,例如

If you need to store just the parameters of the last call then you might use local static variables, e.g.
void ReachDestinationAvoidingNode(unsigned char Xd,unsigned char Yd,unsigned char Xn,unsigned char Yn)
{
  static unsigned char lastXd, lastYd, lastXn, lastYn;


  //..


  lastXd = Xd;
  lastYd = Yd;
  lastXn = Xn;
  lastYn = Yn;
}


如果要在方法调用之间保留这些值,可以将它们放在方法之外并使它们成为全局。
If you want to persist these values between method calls, you can put them off the method and make them global.


远离静态变量,因为如果函数在别处被调用,通常会导致奇怪的行为。



最好使用引用语义。重要的是所有ref值必须是变量值。



Stay away from static variables because the often lead to strange behavior if the functions are elsewhere called.

It is better to use reference semantics. Important all ref values must be variabels.

void ReachDestinationAvoidingNode(unsigned char &Xd,unsigned char &Yd,unsigned char &Xn,unsigned char &Yn)
{
   Xd = 0;// the original Xd gots set
 }

这意味着使用了原始变量的内存,因此你可以写入它们。



注意:类似的原因是使用指针,但在这种情况下它会更加受欢迎。

That means that the memory of the original variables are used and so you can write into them.

Note: a similar why is to work with pointers, but it gets a bit more weired in this scenario.


这篇关于在多次调用时将值存储在函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆