Beginner's question on type checking

I have never programmed in C or C++ before. I am wondering if one can take advantage of type checking to ensure that arguments to a function are in proper order.

Suppose I have a function that take two values which are ultimately integers, xValue and yValue. Is there a way to define the function and/or variables so that:

 a = myFunction(xVariable,yVariable)

is valid but:

a= myFunction(yVariable,xVariable)

generates a compilation error?

Only if you define the types of "x" values and the types of "y" values differently, and specify those types in the formal declaration of the function protoype.
Wouldn't count on it though, unless you have full control of the command-line parameters of the compiler.

You could do this by creating two classes.

XValue and YValue, for instance.

And then declare the function as:

void function(XValue value, YValue value);

Makes sense.

Though then to assign xValue and yValue integer values, I take it I would have to define an int within each class and use something like xValue.content = 3. Or turn to "operator overloading."

Another 'clumsy' way of doing something alike, is to strongly indicate what you expect as parameters by embedding a description in the function name. Something like myFunctionXY();.
Although this will not trigger a compile error by this usage: myFunctionXY(yVal,xVal);, it will look wrong for the programmer, and he/she will most likely (not use the function like that, but if it occurred) see that the parameters are mixed.

Though then to assign xValue and yValue integer values, I take it I would have to define an int within each class and use something like xValue.content = 3. Or turn to "operator overloading."

Yeah.

I would probably make a template class, with operator overloading. And declaring two classes that inherits from the template, with the suitable name and datatype.

Something like:

//Raw type
template <typename datatype>
class Raw {
public:
  Raw();
  Raw(datatype initialValue);
  //operators = != <= >= < > << >> etc.etc.
};
//XValue 
class XValue : public Raw<int> {
public:
  XValue();
  XValue(int initialValue) : Raw<int>(initialValue) { ; }
}

YValue would be like X except for the name... ::slight_smile:

Very good, thanks! The naming method is certainly much easier but this helps me understand class issues a lot better.

Good naming combined with documentation is the key to a good programming style.

As for the "different" types arguments, here is what I found with a standard g++ (not Arduino I mean) :

void f(int x, double y) {
  // do nothing
}

int main() {
  int x = 12;
  double y = 13.0;

  // reverse the arguments
  f(y, x);
}

guess what happens? no warning by default, so be very careful.