Tuesday, October 25, 2022

Initial values in Java and C++

In Java a variable of type int or double has the initial value of zero. But in C++, they can get random values, as you can see in the example below. Note that in C++, the easiest way to set all fields to zero is to use memset.
#include <iostream>
typedef struct {
    int n;
    double values[12];
} DATA;

int main() {
    DATA data;
    std::cout << data.n << ", " << data.values[3] << std::endl;
    memset(&data, 0, sizeof(data)); //set all fields to zero
    std::cout << data.n << ", " << data.values[3] << std::endl;
    std::cout << "Press enter..." << std::endl;
    std::cin.get();
}

No comments:

Post a Comment