HamSelv
HamSelv

Reputation: 11

Can a header file cooperate with code in main?

I've read that an #include header.h is a preprocessor (because of #), which means it gets processed before compilation. Is that why my code can't run? Because I'm trying to make an if statement in main with my function from my header(that takes a parameter) and it won't work.

Source.cpp

#include <iostream>
#include "Header.h"
using namespace std;

int main(){
test(46);

if (test() > 30){
    cout << "great";
}
else{
    cout << "It needs to be higher";
}


    system("PAUSE");
    return 0;
}

Header.h

using namespace std;

    int test(int x){
        return x;
    }

Upvotes: 0

Views: 67

Answers (2)

Logicrat
Logicrat

Reputation: 4468

That isn't the problem. I suspect you might be getting a compiler error message (or linker error) because you have declared test(int x) with an integer parameter and then you call it with no parameter, e.g.: test().

I've modified your code to include an integer result:

int main(){
    int result = test(46); // Save the result of calling the function

    if (result > 30){ // Test the value of the result
        cout << "great";
    }
    else{
        cout << "It needs to be higher";
    }


    system("PAUSE");
    return 0;
}

Upvotes: 3

Superxy
Superxy

Reputation: 147

The test function in Header.h file takes a int as parameter.But in your code you lose it.Pass a int to test function like this.

if (test(42) > 30)

You will get the output: great.

Upvotes: 0

Related Questions