Hello all, header files seemed pretty simple when i first learned about them. until i actually tried to use my own.
The program that i am attempting to create should simply add 1 to 24, but it is using a function found in a header file as a test.
The problem is that i get no errors, but the addition does not happen. This is confusing me quite a bit, and it may be the fact that it's 10 to one in the morning, but i just can't figure it out.

Here is the header file (count.h):

int count (int x) {
	x = x + 1;
	return x;
}

and the main file:

int main () {
#include <iostream>
#include "count.h"
using namespace std;

int num;
num = 24;
cout << num << endl;
count (num);
cout << num << endl;
cin.get();
}

Recommended Answers

All 3 Replies

You aren't storing the variable. Since you are returning an int type, and not passing it by reference, you need this on line 9

num = count(num);

Or if you wanted to pass it by reference you could do this:

void count (int &x) {
	x = x + 1;
}

That would make your current code work.

Functions should never ever be in header files -- only function prototypes. The reason is if you have that header file in two or more *.cpp files then attempt to link those *.cpp files together you will get duplicate declaration errors.

Here is how to correct that problem
count.h

extern int count(int );

main.cpp. Notice how I made a few changes to your program

// Always put the include headers at
// the top of the program, like this:
#include <iostream>
#include "count.h"
using namespace std;

int count (int x) {
	x = x + 1;
	return x;
}

int main () 
{

   int num;
   num = 24;
   std::cout << num << std::endl;
   num = count (num); // you have to capture the return value of count()
   std::cout << num << std::endl;
   std::cin.get();
}

Thanks to both of you, i would have never thought of this now, nevermind at one in the morning.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.