Reputation: 13
I received the error: expected ';', ',' or ')' before numeric constant which i believe is due to me using the macro. The code is meant to calculate the answer to this formula based on a matrix of of MxM where M < 10. For this example, a 3x3 matrix was given to test the code and hence i tried to define M as 3.
#include "stdio.h"
#define M 3
float pfa(int CM[M][M], int M ,int index)
{
int i,j,k;
int numerator;
int denominator;
int answer;
for (i=0; i< M; i++){
if (i != index){
numerator += CM[i][index];
}
}
for (j=0;j<index;j++){
for (k=0; k<M; k++){
if (j != index){
denominator += CM[j][k];
}
}
}
answer = numerator/denominator;
return answer;
}
int main(void)
{
// Variable definitions
int index;
// Note: different initialisation list is needed for different M
int CM[M][M]={{60,2,3},{11,47,7},{27,14,24}};
for (index=0; index<M; index++){
printf("%f \n", pfa(CM,M,index));
}
//0.292308 answers if code is done correctly
//0.123077
//0.076923
}
Upvotes: 0
Views: 117
Reputation: 409176
The preprocessor works by replacing the macros in the code before the actual compilation takes place.
That means, your function declaration
float pfa(int CM[M][M], int M ,int index)
will be compiled as
float pfa(int CM[3][3], int 3 ,int index)
That is of course not a valid function declaration.
Instead, since you will not pass a matrix of differing size, you don't need the M
argument:
float pfa(int CM[M][M], int index)
As an alternative, if the size of the matrix could be different from MxM
and instead be variable, then it's easy to solve as well. Then we need to pass the size first and use it to create the matrix as a variable-length array:
float pfa(size_t size, int CM[size][size], int index)
Note that this can be used even with the current code where the size will always be M
.
Upvotes: 3
Reputation: 213832
The best way to write this program in modern C, is to not use a global constant, but the "pointer to variable-length array" feature:
float pfa (size_t n, int CM[n][n], int index);
...
pfa(M, CM, index)
This removes tight coupling (unnecessarily strong dependency) between the constant and the function.
Upvotes: 0
Reputation: 694
The issue is with the 2nd argument to the function pfa
which is int M
, during preprocessing time M
is replaced with 3
and the argument becomes int 3
, which is not valid, just change the function arguments as
float pfa(int CM[M][M], int size ,int index)
and it should work fine.
Also, you are returning an integer
where the return type of the function is float
. It may cause compiler warning.
Upvotes: 0