printf problem %d and %lld

help
codechef
integers
long_long_int
output
printf

#1

I declared a variable as int ans;

And then used printf as printf("%lld
",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…


#2

%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.


#3

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.


#4

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


#5

I too use gcc only


#6

Have a look here https://ideone.com/P2da7u


#7

and here https://ideone.com/ENe9Ro


#8

http://ideone.com/5FvU0d see this code , the format specifier of printf donot match with the data type still it gives correct answer ,

now see this http://ideone.com/nKavO8 still the format specifier of printf donot match , it gives the wrong answer , so the behaviour is undefined .


#9

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.


#10

Different compilers behave differently as @acodebreaker2 pointed.