1

I have a function,and a matrix declared above it.

int M[100][100];
int function(int row , int col)
{
 if (M[row][col] == 1)return 1;
 return 0;
}

My question is,how can the function acces the matrix if i don't pass it as a parameter,like:

int function(int row , int col , int X[][100])

Thank you.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

3 Answers3

2

You can make the matrix a global variable (not recommended) to be able to access it in a function without passing it as a parameter. See this answer on variables with file scope global access vs variables with process scope global access.

SCCC
  • 341
  • 3
  • 13
2

I have a function,and a matrix declared above it

The matrix and the function are both declared in the same declarative region (it seems in the global namespace). So as the matrix is declared before the function definition then the matrix declaration is visible in the body of the function.

That is according to the unqualified name lookup (The C++ 17 Standard, 6.4.1 Unqualified name lookup)

6 In the definition of a function that is a member of namespace N, a name used after the function’s declarator-id shall be declared before its use in the block in which it is used or in one of its enclosing blocks (9.3) or shall be declared before its use in namespace N or, if N is a nested namespace, shall be declared before its use in one of N’s enclosing namespaces.

If you will exchange the matrix declaration and the function definition like

int function(int row , int col)
{
 if (M[row][col] == 1)return 1;
 return 0;
}

int M[100][100];

then the compiler will issue an error because the name M used in the function body will not be found before its usage.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-1

You've made the matrix a global variable, meaning it's available to all the functions defined beneath it (and, with an appropriate extern declaration, others too!).

Globals are not the most widely recommended thing to use, as it makes data flow harder to follow and prove.

You might consider making the matrix into a class (with the array a data member of the class), then function can be a member function ("method") of this class. This keeps everything neatly packaged together. Member functions automatically have access to other members.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35