printf problem %d and %lld

I declared a variable as int ans;

And then used printf as printf("%lld\n",ans); I got wrong answer.

When I changed it to %d I got AC.

But in my computer I was getting correct output. Any explanation why??

Any help is appreciated…

%lld is used for printing long long int and %d is used for printing integer variables. May be on your computer you were using different compiler so you were getting right answer. Codechef uses gcc compiler and hence you got wrong answer.

What can happen if printf is called with a wrong format string?

Anything can happen. It is Undefined behavior!
Undefined behavior means that anything can happen. It may show you results which you expect or it may not or it may crash. Anything can happen and you can blame no one but yourself about it.

Reference:

c99 Standard: 7.19.6.1:

para 9:

If a conversion specification is invalid, the behavior is undefined.225) If any argument is not the correct type for the corresponding coversion specification, the behavior is undefined.

2 Likes

@the65bit but why in my computer i get the same output for both ur codes?? i am using gcc 4.8.1

I too use gcc only

Have a look here P2da7u - Online C++ Compiler & Debugging Tool - Ideone.com

1 Like

and here ENe9Ro - Online C++ Compiler & Debugging Tool - Ideone.com

1 Like

5FvU0d - Online C++ Compiler & Debugging Tool - Ideone.com see this code , the format specifier of printf donot match with the data type still it gives correct answer ,

now see this nKavO8 - Online C++ Compiler & Debugging Tool - Ideone.com still the format specifier of printf donot match , it gives the wrong answer , so the behaviour is undefined .

1 Like

when the code is erroneous, different compilers may behave differently. You have to make sure that the code you write is correct from your side.

Different compilers behave differently as @acodebreaker2 pointed.