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.

9
  • 1
    V is not defined anywhere, and the compiler is telling you about it. Commented Jul 25, 2019 at 4:00
  • 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 Commented Jul 25, 2019 at 4: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; Commented Jul 25, 2019 at 4:07
  • 2
    See also: Why should I not #include <bits/stdc++.h>? Commented Jul 25, 2019 at 4:35
  • 1
    std::vector<std::vector<int>> might be more appropriate, (or create dedicated class Matrix or use on from existing lib). Commented Jul 25, 2019 at 7:11

1 Answer 1

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()  
{  
   /* */
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.