cfiset
September 19, 2017, 11:47pm
1
Hi!
I try to do a function that he will return 3 value. This's woking, but it's the right way?
Thank
int h,m,s;
void GetTime(int & h, int & m, int & s);
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
GetTime(h,m,s);
Serial.begin(115200);
Serial.println();
Serial.println();
Serial.print("H = ");
Serial.print(h);
delay(5000);
}
void GetTime(int & h, int & m, int & s){
h = 12;
m = 5;
s = 25;
return;
}
cfiset
September 20, 2017, 12:10am
3
Thank for the answer. And if I don't set h,m,s as global variable, like this:
void GetTime(int & h, int & m, int & s);
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
int h,m,s;
GetTime(h,m,s);
Serial.begin(115200);
Serial.print(h);
delay(5000);
}
void GetTime(int & h, int & m, int & s){
h = 12;
m = 5;
s = 25;
return;
}
but this mean I will declare/initalize h,m and s evey loop...
cfiset:
I try to do a function that he will return 3 value. This's working, but it's the right way?
Using a "structure" gives better encapsulation. It allows you to treat the three fields as a single unit.
Note: Since the time fields don't need to store values less than 0 or greater than 255 I use the 'byte' (unsigned char) type.
struct Time {
byte hour;
byte minute;
byte second;
};
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
struct Time localTime;
// put your main code here, to run repeatedly:
GetTime(localTime);
Serial.print("hour = ");
Serial.println(localTime.hour);
Serial.print("minute = ");
Serial.println(localTime.minute);
Serial.print("second = ");
Serial.println(localTime.second);
Serial.println();
Serial.println();
delay(5000);
}
void GetTime(struct Time &time) {
time.hour = 12;
time.minute = 5;
time.second = 25;
}
The old-school way would be to pass a pointer instead of a reference:
void GetTime(struct Time *time) {
time->hour = 12;
time->minute = 5;
time->second = 25;
}