简体   繁体   中英

How to initialize global variables via a function in C++

I am learning C++. I want to have a function to initialize my variables. For example:

#include <iostream>

double a,b
void Initializer ( double x, double y)
{
    a = x;   //a and b are global variables.
    b = y;
}
int main()
{
    Initializer(0.,4.);
    std::cout<<a<<" "<<b<<std::endl;
    return 0;
}

However, I get garbage for my global variables. For example I call initializer(0.,4.) , and I expect a==0 and b==4 ; however when I print the values they are not 0,4 respectively.

I do not see anything wrong about your code (except the formatting). This is the way you can initialize global variables in both C and C++ (complete, formatted example):

#include <iostream>

void Initializer(double x, double y);

using namespace std;

double a, b;

void Initializer(double x, double y) {
    a = x;  // a and b are global variables.
    b = y;
}
int main() {
    Initializer(0.0, 4.0);
    cout << a << " " << b << endl;

    return 0;
}

Note that this line: cout << a << " " << b << endl; (together with the corresponding include and using namespace std; ) is using C++ streams. The rest could also be compiled as C code.

It would also be more readable if you would provide doubles like that: Initializer(0.0, 4.0); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM