#Define utility in C ++

Hey guys! I just learned this code from a tutorial for adding a matrix in C ++ by reading the values ​​from a file? I wanted to ask what does #define do here? What is so special about this? And how does this differ from separately declaring M and N as int or char in main ???? Thanks in advance! the 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();
}
+3
source share
4 answers

This is the preprocessing directive of the form.

#define identifier token-sequence

The preprocessor starts before the compiler converts your code for use in the compiler. The order is as follows:

  • Trigraph Replacement
  • Line merging
  • Defining and expanding macros

So, with #defineyou can have character manipulation (macro substitution).

Whenever M is seen, 4 will be replaced.

 void matrixSum (int P[4][5], int Q[4][5], int R[4][5]);  // ..etc

- const .

C

// Some fileA.c  
const int M; // initialize

// Some fileB.c
const int M = 4; // defined

, , , , , .

0

#define , #, - , C .

, #define , , , "4" . , . , , #defines . #defines . - #define, , #define, ( ), #define. , C, #defines.

+3

Thought const int M = 4;and const int N = 5;forced the author shake in his shoes because of the colossal 8 bytes of memory, so instead he used #define.

+3
source

As a side note, a more general solution would be to use a function template:

template<size_t M, size_t N>
void matrixSum (int (&P)[M][N], int (&Q)[M][N], int (&R)[M][N]);

template<size_t M, size_t N>
void matrixSum (int (&P)[M][N], int (&Q)[M][N], int (&R)[M][N])
{
  for (int i=0; i<M; i++)   
    for (int j=0; j<N; j++) 
       R[i][j] = P[i][j] + Q[i][j];
}
int main () 
{

 const int M = 4; //now in main!
 const int N = 5;

 ifstream f;
 int A[M][N];
 int B[M][N];
 int C[M][N];

 //same as before
}

I think this is better than using #definebecause using constor enumhelps in debugging. More detailed explanation here:

C ++ - enum vs. const vs. #define

+2
source

All Articles