-2

Why is this printing 0, instead of 6?

main(void) {

   int i, j;

   int T[3][3] = {{5,1,3},{3,5,6},{5,6,3}};

   printf("%f", T[1][2]);
return 0;
}
Marcelo
  • 77
  • 9
  • 1
    Undefined behaviour. `%f` tells `printf()` to expect a `double`, but your code passes an `int`. Use the `%d` format instead. – Peter Jul 01 '20 at 14:11
  • 1
    dupe of [Why does printf("%f",0); give undefined behavior?](https://stackoverflow.com/questions/38597274/why-does-printff-0-give-undefined-behavior) or many more. also, `main()` must return `int`. – underscore_d Jul 01 '20 at 14:13
  • If you are really using C++, as your tag suggests (rather than C as your code suggests) you could use iostreams or the [fmt](https://github.com/fmtlib/fmt) library to avoid worrying about matching `printf` specifiers to parameter types. – Arthur Tacca Jul 01 '20 at 14:13
  • To find detailed reason to print 0, you will need information about your environment such as sizes of `int` and `double`, and the ABI (how to pass integer and floating-point arguments). – MikeCAT Jul 01 '20 at 14:14

2 Answers2

2

You invoked undefined behavior by passing printf() wrong type and you got the result by chance.

%f is for printing double, not int. To print int, you should use %d.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
-1

it is not printing zero, in reality, it is returning 0, this happens whenever there is error.

the error to your code is that you used %f which is for printing double, since you have input in form of int, you need to use %d. this will solve the error and hence not return 0.

underscore_d
  • 6,309
  • 3
  • 38
  • 64
  • This is wrong. A return code of `0` means success. There's even a standard macro for that: `EXIT_SUCCESS`. In addition, C does not guarantee to return a code that would actually indicate failure "whenever there is **error**", if "error" is defined vaguely, because that risks misleading newbies into thinking that the runtime will save them from shooting their foot off. The program has undefined behaviour because of the wrong format specifier, but that says nothing about what it will return. The behaviour is undefined. A value of `0` is not guaranteed either as output of `printf()` or exit code. – underscore_d Jul 01 '20 at 16:24