Pages: [1]   Go Down
Author Topic: Approach to computing a value once in a library?  (Read 209 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Full Member
***
Karma: 0
Posts: 138
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'll try to describe this the best I can...

Let's say my sketch has a constant "foo=100" and I have a library called "libby" with a function called "funk".  Inside of funk there is a variable "boo" that will *always* be foo/2.  My question is, what is the approach that would allow the computation to happen only once even though funk is called many times in the sketch.

For example, is this a valid approach?
Code:
Sketch:
#include <libby.h>
const byte foo=100;
libbyClass libbyObject;
setup(){}
loop(){
libbyObject.funk(foo);
}

libby.cpp:
#include "libby.h"
libbyClass::libbyClass(){}

void libbyClass::funk(byte var){
static byte boo=var/2;
}

libby.h:
#ifndef libby_H
#define libby_H
#include "Arduino.h"

class libbyClass{

public:
  libbyClass();
  void funk(byte var);

};
# endif

Thanks!
Logged

UK
Offline Offline
Shannon Member
****
Karma: 184
Posts: 11159
-
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'd have the sketch pass in the value through a constructor or configuration method, and design the sketch so that the value was only passed on once. In your example, calling funk() repeatedly from loop() doesn't make sense; it would be better called once from setup(), or pass the value in via a constructor argument.
Logged

I only provide help via the forum - please do not contact me for private consultancy.

Offline Offline
Full Member
***
Karma: 0
Posts: 138
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'd have the sketch pass in the value through a constructor or configuration method, and design the sketch so that the value was only passed on once. In your example, calling funk() repeatedly from loop() doesn't make sense; it would be better called once from setup(), or pass the value in via a constructor argument.

I think I understand how to make the computation in the constructor, however I am not at all clear how I should declare the variable "boo" in the libby.cpp and libb.h if I take that approach.  Could you provide some guidance?

Thanks
Logged

Global Moderator
Offline Offline
Brattain Member
*****
Karma: 452
Posts: 18694
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Like this:

Code:

class libbyClass
{
private:
  const byte boo;
  
public:
  // constructor
  libbyClass(const byte fubar) : boo (fubar / 2) { }
  
  // some method
  void funk();

};

void libbyClass::funk()
  {
  Serial.println (boo);
  }

const byte foo=100;
libbyClass libbyObject (foo);

void setup ()
  {
  Serial.begin (115200);
  libbyObject.funk ();
  }  // end of setup

void loop ()  { }
  
Logged

Pages: [1]   Go Up
Jump to: