Using void in header file

c++

Solution

Unlike variables, you cannot give a new value to a function. So here is what the compiler thinks:

"Oh, OK, when you say `IncrementAndPrint`, what you mean is this function here at the top of the file".

Then it sees `print_auto` and learns what that means. But then you try to tell it that `IncrementAndPrint` actually means this other function, and the compiler gets confused. "But you already told me what `IncrementAndPrint` means!", complains the compiler.

This contrasts with variables (in some way), where you can say:

int x = 0;
x = 6;

The compiler understands that at one point, `x` has the value `0`, but then you say "`x` is different now, it means `6`.". However, you cannot say:

int x = 0;
int x = 6;

Because when you include a type before a variable name, you are defining a new variable. If you do not include a type, you are just assigning to an old one.

You will have to give `IncrementAndPrint` a different name.

Alternatively, you could have them take different arguments, for instance, `void IncrementAndPrint(int x);` vs. `void IncrementAndPrint(double y);`. I don't recommend that here because you don't need the argument.

Another possibility is to use a namespace. It would look something like this:

namespace automatic_variables {

void IncrementAndPrint() {
    // automatic variable version
}
void print() {
    // automatic version
}
}
namespace static_variables {

void IncrementAndPrint() {
    // static variable version
}
void print() {
    // static version
}
}

Problem

This is my header file, auto vs static.h ``` #include "stdafx.h" #include <iostream> void IncrementAndPrint() { using namespace std; int nValue = 1; // automatic duration by default ++nValue; cout << nValue << endl; } // nValue is destroyed here void print_auto() { IncrementAndPrint(); IncrementAndPrint(); IncrementAndPrint(); } void IncrementAndPrint() { using namespace std; static int s_nValue = 1; // fixed duration ++s_nValue; cout << s_nValue << endl; } // s_nValue is not destroyed here, but becomes inaccessible void print_static() { IncrementAndPrint(); IncrementAndPrint(); IncrementAndPrint(); } ``` And this is my main file, namearray.cpp ``` #include "stdafx.h" #include <iostream> #include "auto vs static.h" using namespace std; int main(); // changing this to "int main()" (get rid of ;) solves error 5. { print_static(); print_auto(); cin.get(); return 0; } ``` I'm trying to print (cout) 2 2 2 2 3 4 Errors: I feel that my mistake is just using void in the header file. How can I change the header file so that my code will work? Reference: code from learncpp

Original source

Related problems