i have a variable "float PI = 3.146;" in a header file called "evar.h" but when i use the variable PI in my main functoin it only comes out as "3" , i have to explictly type cast it for the number "3.146" to be printed out

how could i overcome this problem ?

Well, you could post the code for starters.

Well, you could post the code for starters.

well heres the header file

#ifndef _EVAR_H_
#define _EVAR_H_

float PI = 3.146;

#endif // _EVAR_H_

and the main code file

#include <cstdlib>
#include <iostream>
#include "evar.h"

using namespace std;

int main(int argc, char *argv[])
{
    extern float PI;
    
    cout << "PI Is Equal To: " << PI << endl;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

OUTPUT

PI Is Equal To: 3

this is just to try out external variables because i'm still learning

Try moving line 9 to line 6.

Try moving line 9 to line 6.

its ok now , i just omitted the extern decleration and it worked lol

It shouldn't have.

Problem #1) Never define a variable in a header file. The statement float PI = 3.146; should only be made in a source file. If you add the header to 4 source files, you will have 4 definitions of PI causing lots of errors.

Problem #2) The extern statement goes in the header file so other sources that include the .h file know that PI will be defined in another source.

It shouldn't have.

Problem #1) Never define a variable in a header file. The statement float PI = 3.146; should only be made in a source file. If you add the header to 4 source files, you will have 4 definitions of PI causing lots of errors.

Problem #2) The extern statement goes in the header file so other sources that include the .h file know that PI will be defined in another source.

well this is how my class thought me to do it, its called external variables they said ,

it is just like defining constants in a header file and the extern keyword tells the compiler that that variable is external and not to confuse with other "PI" variables from other namespaces ect...

Try this:

cout << "PI Is Equal To: " << fixed << PI << endl;

well this is how my class thought me to do it, its called external variables they said ,

it is just like defining constants in a header file and the extern keyword tells the compiler that that variable is external and not to confuse with other "PI" variables from other namespaces ect...

I believe you misunderstood your class. And if not, you need an instructor that knows the language because your understanding is not correct.

I believe you misunderstood your class. And if not, you need an instructor that knows the language because your understanding is not correct.

ok then lol, be like that

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.