I am converting blocks of C code into Java, and I came across some syntax that I can not quite understand. The first one uses #define to create a function. I personally have not seen #define to create functions before. I also just found out in this post that this is really a macro. Below you will see what I attempted to interpret this code as in Java.
Here is the C code:
#define mat_elem(a, y, x, n) (a + ((y) * (n) + (x)))
Which I then converted to this in Java:
public double mat_elem(double a, int y, int x, int n){
return (a + ((y) * (n) + (x)));
}
Now the real issue here, is this block of code that also uses #define.
Code in C:
#define A(y, x) (*mat_elem(a, y, x, n))
I have not converted into Java yet because I'm not too sure what is going on.
I first thought that #define A(y, x) creates a data type that is equal to whatever get's returned in (*mat_elem(a, y, x, n)). However, the pointer that they are using in front of mat_elem is throwing me off.
I was thinking of doing something like this in Java:
public double[] fillA(double y, double x){
double [] A = new double [100];
for(int i = 0; i < some_var; i++){
A[i] = mat_elem(a, y, x, n);
}
return A;
}
I'm sure something like this would work, however my main concern is understanding what the C code is really doing, and If my imperfect code is equivalent to the code in C.
#definedoesn't define a function, but a macro that is expanded each time where it is used. Ifais a pointer to a matrix, it returns a pointer to an element inside the matrix. In Java, you can define the matrix as a two-dimensional array of double (double[][]) and (after you have properly initialised it) you won't need thismat_elemA(3, 4) = 5.0;then this is first "replaced" with*mat_elem(a, 3, 4, n) = 5.0;which is "replaced" with*((a + ((3) * (n) + (4))) = 5.0;In Java, just saya[3][4] = 5.0;