0

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 ?

4
Contributors
9
Replies
10
Views
6 Years
Discussion Span
Last Post by RyanMcMillan
0

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

Edited by RyanMcMillan: n/a

0

Try moving line 9 to line 6.

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

0

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.

0

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...

0

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.

Edited by WaltP: n/a

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.