1

Hey I am currently trying to switch from c++ to c and wonder if there is any way to avoid this because there are no more classes to use the implicit this->:

void func(Data *const longAndExpressiveName)
{
    longAndExpressiveName->x += longAndExpressiveName->vel.x;
}

Because even if the name is not that long it still makes the code much harder to understand.

Lion King
  • 32,851
  • 25
  • 81
  • 143
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/203552/discussion-on-question-by-earl-of-lemongrab-how-to-avoid-lots-of-structpointer). – Samuel Liew Dec 03 '19 at 19:49

2 Answers2

1

There is no syntax to accomplish your direct ask in C. The closest you can come is to create temporary variables.

int *xptr = &longAndExpressiveName->x;
int vel_x = longAndExpressiveName->vel.x;

*xptr += vel_x;

Your desire to use longAndExpressiveName is misplaced in this case, because in C++, you are coming from a syntax where longAndExpressiveName is not passed as a parameter, and the parameter is implicitly hidden by the implicit this->. The C++ syntax for the caller would be:

longAndExpressiveName->func();

And you are translating that into:

func(longAndExpressiveName);

And then you propagate that same name to the parameter name. While it may be appropriate for the caller to refer to the pointer with a long and expressive name, it is not really helpful to the "member" function. But, what would be helpful is if the function is named so that you know it is meant to do something to a particular kind of structure.

void func_Data(Data * const d) {
    d->x += d->vel.x;
}

Which better captures the original C++ syntax:

void Data::func () {
    x += vel.x;
}
jxh
  • 69,070
  • 8
  • 110
  • 193
  • Alright thank you. What are your doing in your code? Because I kind of don't want to create temporary variables just for naming – Earl of Lemongrab Dec 03 '19 at 17:40
  • There is nothing wrong in creating temp variables just for convenience. The compiler is usually smart enough to optimize it out. – Eugene Sh. Dec 03 '19 at 17:42
  • @EarlofLemongrab: I would use descriptive member names, and shorter names to the containing structure. Consider [this](https://stackoverflow.com/a/17622474/315052). – jxh Dec 03 '19 at 17:44
0

C does not have any magic syntax to do what you want explicitly. However, you can just assign the parameter with a long and expressive name to a variable of the same or compatible type with a shorter name:

void func(Data *const longAndExpressiveName)
{
    Data *const t = longAndExpressiveName;
    t->x += t->vel.x;
}

This cuts down on typing if the long and expressive name would otherwise be repeated a lot in the function.

Ian Abbott
  • 15,083
  • 19
  • 33