This will not work the way you would like it to. I assume you would like to do something like the below code example:
typedef struct {
int x;
} MyStruct;
MyStruct *newMyStruct(int x){
MyStruct *this;
this->x = x;
return this;
}
task main() {
MyStruct *myStruct = newMyStruct(1);
}
The code will compile fine, but running it fails when trying to set the value of this->x, because ROBOTC does not support dynamic memory allocation.
If you instead try running a program similar to yours, like the one below:
typedef struct {
int x;
} MyStruct;
MyStruct *newMyStruct(){
MyStruct *this;
return this;
}
task main() {
MyStruct *myStruct = newMyStruct();
myStruct->x = 1;
}
It will also fail when trying to set the value of myStruct->x, again because ROBOTC does not support dynamic memory allocation.
You can attempt to create a workaround, using references rather than pointers like so:
typedef struct {
int x;
} MyStruct;
MyStruct *newMyStruct(int x){
MyStruct this;
this.x = x;
return &this;
}
task main() {
MyStruct *myStruct1 = newMyStruct(1);
MyStruct *myStruct2 = newMyStruct(2);
writeDebugStream("myStruct1->x = %d\n", myStruct1->x);
writeDebugStream("myStruct2->x = %d\n", myStruct2->x);
}
The program compiles and runs just fine, however it does not perform as intended. myStruct1->x and myStruct2->x both have a value of 2, because the reference returned by newMyStruct is the same both times the function is called.
Thus, the solution presented by @Cody is your best bet. I’d like to make a note about his method, which I have rewritten below to stay consistent with my other examples:
typedef struct {
int x;
} MyStruct;
MyStruct *newMyStruct(MyStruct &this, int x){
this.x = x;
return this;
}
task main() {
MyStruct myStruct;
newMyStruct(myStruct, 1);
}
I wanted to point out that the “&” before the MyStruct parameter in the newMyStruct function works in C++, but would not be valid in C, as C does not support pass-by-reference. However, it works in ROBOTC, as this is one of the C++ features supported by ROBOTC.
In C, you could accomplish the same thing with the following code (which I have written to work in ROBOTC):
typedef struct {
int x;
} MyStruct;
MyStruct *newMyStruct(MyStruct *this, int x){
this->x = x;
return this;
}
task main() {
MyStruct myStruct;
newMyStruct(&myStruct, 1);
}
Some argue that using the C++ pass-by-reference method is better because it is cleaner, while others argue that it is more ambiguous, because it is impossible to know if the function newMyStruct can modify myStruct without seeing the function prototype. Take that as you’d like, I prefer the second, C method. ROBOTC only has a tiny number of C++ features anyway.