0

I am trying to work with multi-dimensional arrays. My goal is to have a separate file for my matrix functions, however I am having trouble with setting the value of V.

Error : ‘V’ was not declared in this scope Since this error statement is very broad, I could not find a satisfactory answer on my searches.

This is what I want to implement.

main.cpp

#include <bits/stdc++.h> 
using namespace std;
#include "prims.h"

int main()  
{   int V = 5;
    int graph[V][V] = { {... },  
                        {... },  
                        {... },   
                        {... },   
                        {... } };    
    func1(graph);
    func2(graph); 
    return 0;  
}

prims.h

#ifndef PRIMS_H
#define PRIMS_H
#include <bits/stdc++.h> 
using namespace std;

int func1(int graph[V][V]);
int func2(int graph[V][V]);

#endif

prims.cpp

#include <bits/stdc++.h> 
using namespace std;
#include "prims.h"

int func1(int graph[V][V])  
{  
  // function
} 

int func2(int graph[V][V])  
{  
  // function
}

Please comment below if more clarification is required. Thank you.

ashish-ucsb
  • 101
  • 6
  • 1
    `V` is not defined anywhere, and the compiler is telling you about it. – paddy Jul 25 '19 at 04:00
  • I understand that, how do I implement what I want ? – ashish-ucsb Jul 25 '19 at 04:04
  • Use a namespace – solarflare Jul 25 '19 at 04:05
  • 1
    as the above comments already suggest 'V' needs to be defined somewhere OR if its defined somewhere then that header is not included. use a class and make those functions as members of the class OR if that is too much work then use a namespace. [more about namespace here](https://www.learncpp.com/cpp-tutorial/4-3b-namespaces/) – dorKKnight Jul 25 '19 at 04:07
  • 2
    Are you serious? You are referencing an identifier that doesn't exist. What value do you want? 42? Okay, so define it as a constant, maybe in `prims.h` _i.e._ `const int V = 42;` – paddy Jul 25 '19 at 04:07
  • Sorry, I forgot to put `V` in my question. I'll make the edit. – ashish-ucsb Jul 25 '19 at 04:10
  • 2
    See also: [Why should I not #include ?](https://stackoverflow.com/q/31816095/673852) – Ruslan Jul 25 '19 at 04:35
  • Your current code has `main` changing the types of the parameters that `func1` takes. That can't work. How would code in `func1` even know the value of `V` since it's not passed in? – David Schwartz Jul 25 '19 at 07:07
  • 1
    `std::vector>` might be more appropriate, (or create dedicated `class Matrix` or use on from existing lib). – Jarod42 Jul 25 '19 at 07:11

1 Answers1

2

Since you want to set the value from main, one alternative is to declare V as global variable in main and as extern const int in prims.h, so that it is visible in prmis.cpp as well.

prims.h

extern const int V;

main.cpp

const int V = 5; //declared as global in main
int main()  
{  
   /* */
}
seccpur
  • 4,996
  • 2
  • 13
  • 21