0

i have a little problem with printf and i don't know why !

=>kernel.h

#ifndef KERNEL_H
#define KERNEL_H

namespace kernel
{
    extern const double h;
}

#endif // KERNEL_H

=>kernel.cpp

#include <kernel.h>

namespace kernel
{
    const double kernel::h=85.0;
}

=>main.cpp

#include "kernel.h"
#include <iostream>
//#include <cstdio>//With cstdio, it is the same problem !

int main(int argc, char *argv[])
{

    using namespace kernel;

    double a = h;

    printf("printf a is %d\n",a);
    std::cout<<"std::cout a is " << a << std::endl;

    printf("printf h is %d\n",h);
    printf("printf kernel::h is %d\n",kernel::h);
    std::cout << "std::cout h is " << h << std::endl;

    return 0;
}

And my output on my console is :

printf a is 0
std::cout a is 85
printf h is 0
printf kernel::h is 0
std::cout h is 85

Why printf doesn't work? Because it is a C function ?

Thanks

awat
  • 175
  • 1
  • 1
  • 9
  • Is it really necessary to include kernel.h in kernel.cpp? – BillyJean May 09 '13 at 17:11
  • It is not an error, but the definition in the cpp file is excessive. You could do either `const double kernel::h=85.0` (without reopening the namespace), or just `const double h=85.0` if you reopened it. You kinda "did both", which is redundant. – AnT stands with Russia May 09 '13 at 17:11

2 Answers2

2

%d is for integers, you are trying to print a double as an int. I think you'd want %lf for long float for doubles? Never actually printf'd a double before.

RandyGaul
  • 1,915
  • 14
  • 21
  • ok my bad ! I'm really stupid ! It's work correctly with %f , you are right %d, it's only for int... Thanks a lot – awat May 09 '13 at 17:07
2

that is because you are printing it as an integer. Try %lg or %lf

printf("printf kernel::h is %lg\n",kernel::h);

If you turn on warnings the compiler would have told you the problem. -Wformat

or just use std::cout and you won't have this kind of problems

std::cout << kernel::h;
stardust
  • 5,918
  • 1
  • 18
  • 20