0

I have the following header file:

#include <iostream>
const int x = 15;
const int y = 15;
const double lx = 2 / (x - 1);
const double ly = 2 / (y - 1);

And the following code:

#include "t.h"
int main()
{
    std::cout << "x: " << x << std::endl;
    std::cout << "y: " << y << std::endl;
    std::cout << "lx: " << lx << std::endl;
    std::cout << "ly: " << ly << std::endl;
    std::cout << "lx / 2: " << lx / 2 << std::endl;
    std::cout << "ly / 2: " << ly / 2 << std::endl;
}

Output:

x: 15
y: 15
lx: 0
ly: 0
lx / 2: 0
ly / 2: 0

And for some reason I cant figure out why lx and ly output as 0 and obviously when I operate with them its also 0. What am I doing wrong?

Thanks

dominique120
  • 1,170
  • 4
  • 18
  • 31
  • 3
    This has nothing to do, whatsoever, with variables in header files. Dividing 2 by 14 is 0. That's how integer division works, in C++. If you want a fractional result, you must divide `double` values in the first place, like `2.0` by `14`, or divide `2` by `14.0`. – Sam Varshavchik Dec 31 '19 at 22:37
  • 3
    Sidenote: defining variables in headers often leads to different problems at link time. Look up `extern` in your favorite C++ reference for a discussion of this problem and how to solve it. – user4581301 Dec 31 '19 at 22:44
  • 1
    @user4581301 although `const` globals have internal linkage in C++ unless you specifically write `extern` – M.M Dec 31 '19 at 23:17
  • Yet another difference with C. Sad that I'm learning this one now. – user4581301 Dec 31 '19 at 23:26

0 Answers0