Skip to content

Instantly share code, notes, and snippets.

@indraastra
Last active January 19, 2016 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indraastra/0a3e25485fb58d788081 to your computer and use it in GitHub Desktop.
Save indraastra/0a3e25485fb58d788081 to your computer and use it in GitHub Desktop.
Returning Structs
#include "pumpstate.h"
SYSTEM_MODE(AUTOMATIC);
SYSTEM_THREAD(ENABLED);
void setup() {
Serial.begin(9600);
delay(1000);
initPumpState();
const pumpState& s = getPumpState();
// Default state.
Serial.println(s.RPM);
Serial.println(s.Watts);
// Should FAIL to compile.
//s.Watts = 100;
// State A.
Serial.println(StateA->RPM);
Serial.println(StateA->Watts);
// Should FAIL to compile.
//StateA->Watts = 100;
// State B.
Serial.println(StateB->RPM);
Serial.println(StateB->Watts);
// Beware, you can easily twist the compiler's arm.
//pumpState* bad_s = StateA; // Compiler error.
pumpState* bad_s = (pumpState*)StateA; // No error!
bad_s->RPM = 0;
bad_s->Watts = 60000; // Muahaha!
}
void loop() {
}
#include "pumpstate.h"
// Storage for the default pumpState.
pumpState defaultState = {
10U,
10000U
};
pumpState state1 = {
100U,
20000U
};
pumpState state2 = {
200U,
30000U
};
const pumpState* const DefaultState = &defaultState;
const pumpState* const StateA = &state1;
const pumpState* const StateB = &state2;
void initPumpState() {
// Initialize and set any defaults here.
// You could even forego the default settings at the site
// of declaration and set all the variables here.
defaultState.Error = 0;
state1.Error = 0;
state2.Error = 0;
}
const pumpState& getPumpState() {
return defaultState;
}
#pragma once
#include <cstdint>
struct pumpState {
uint16_t Watts;
uint16_t RPM;
uint8_t Error;
};
// Returns a reference to an immutable pumpState.
void initPumpState();
const pumpState& getPumpState();
// Alternate method: an opaque global pointer.
extern const pumpState* const DefaultState;
extern const pumpState* const StateA;
extern const pumpState* const StateB;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment