1

First time using Structs in Arduino since school I am assuming that the structs would behave like objects and when I call them directly it does I would expect this code to print

1 1
2 1
1 2
2 2
1 3
2 3
1 4
2 4

But I get

1 1
2 1
1 1
2 2
1 1
2 3
1 1
2 4

Sample of the code that I used

// Example program
#include <iostream>
#include <string>  
struct Testtype{
    Testtype(int A) : foo(A){}
    int foo;
    int bar = 0;
   };
Testtype Test1 = Testtype(1);
Testtype Test2 = Testtype(2);
void fun(Testtype Test){
   Test.bar++;
   Test2.bar++;
   std::cout << Test.foo;
   std::cout << " " << Test.bar << "\n";
   std::cout << Test2.foo;
   std::cout << " " << Test2.bar << "\n";
}
void loop(){
   fun(Test1);
}
int main()
{
  int i =0;
  while (i < 4){
    loop();
    i++;
  }
}
John Puhr
  • 53
  • 4
  • 1
    TL;DR of the dupe: You need to pass by reference if you want to modify the object you are passing to the function. Otherwise you are making copies and modifying the copies. – NathanOliver Oct 24 '19 at 20:24
  • 1
    It's also possible to pass by value and change the object. Libraries like opencv do this. Instead of values you can store pointers in your object: `int bar = 0;` => `std::shared_ptr bar = std::make_shared(0);`. You would have to adept your code and it's not recommended for this example but there are other use cases where you can use this. – Thomas Sablik Oct 24 '19 at 21:02

0 Answers0