I just found out this code from a tutorial for matrix addition in c++ by reading the values from a file-
I wanted to ask what does #define does here? What is so special in it? And how is it different from separately declaring M and N as int or char in main?
code
#include <iostream>
#include <fstream>
using namespace std;
#define M 4
#define N 5
void matrixSum (int P[M][N], int Q[M][N], int R[M][N]);
void matrixSum (int P[M][N], int Q[M][N], int R[M][N]) {
for (int i=0; i<M; i++) // compute C[][]
for (int j=0; j<N; j++)
R[i][j] = P[i][j] + Q[i][j];
}
int main () {
ifstream f;
int A[M][N];
int B[M][N];
int C[M][N];
f.open("values"); // open file
for (int i=0; i<M; i++) // read A[][]
for (int j=0; j<N; j++)
f >> A[i][j];
for (int i=0; i<M; i++) // read B[][]
for (int j=0; j<N; j++)
f >> B[i][j];
matrixSum (A,B,C); // call to function
for (int i=0; i<M; i++) { // print C[][]
for (int j=0; j<N; j++)
cout << C[i][j] << " ";
cout << endl;
}
f.close();
}
It is a preprocessor directive of the form
The preprocessor runs before the compiler transforms your code for use in the compiler. The order is as follows:
So with the
#defineyou can have character manipulation (macro substitution).Whenever M is seen 4 will be substituted.
The compiler will then see
The other way would be to use the const qualifier on a global variable.
In C, it would be
So I would say try to avoid when possible because macros are a form of text substitution, they do not obey scope and type rules.