1

I was solving C programming Questions and I came across this

#include<stdio.h>
int main()
{
   int x=100,y=200,z=300;
   printf("%d..%d..%d");
}

I expected an error but the output was 300..200..100

Can anyone explain this output?

dandan78
  • 13,328
  • 13
  • 64
  • 78
shashank
  • 400
  • 8
  • 25

4 Answers4

2

%d in printf expects int type argument. You are passing no arguments. Its a constraint violation and ultimately your program invokes undefined behavior.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

your code has so many warning says..

root@jeegar:~/test# gcc -Wall testprintf.c 
testprintf.c: In function ‘main’:
testprintf.c:5:4: warning: too few arguments for format
testprintf.c:4:20: warning: unused variable ‘z’
testprintf.c:4:14: warning: unused variable ‘y’
testprintf.c:4:8: warning: unused variable ‘x’
testprintf.c:6:1: warning: control reaches end of non-void function

when i run your code it shows different result each time.

root@jeegar:~/test# ./a.out 
1822880072..1822880088..4195632root@jeegar:~/test# 
root@jeegar:~/test# 
root@jeegar:~/test# ./a.out 
-1388515512..-1388515496..4195632root@jeegar:~/test# 
root@jeegar:~/test# 
root@jeegar:~/test# 
root@jeegar:~/test# ./a.out 
401499528..401499544..4195632root@jeegar:~/test# 

So here it's undefined behavior

It may be posible that undefined behavior result same value as yours

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
0

When you use "%d" you are saying that a integer input should go there, but you never supply the integer to use. You need to add the integers as arguments after the string, like this:

#include<stdio.h>
int main()
{
   int x=100,y=200,z=300;
   printf("%d..%d..%d", x, y, z);
}

If you run printf("%d..%d..%d"); you will still get an output, but it will be some random un-initialized values.

Johan Hjalmarsson
  • 3,433
  • 4
  • 39
  • 64
0

printf is

int printf(const char*, ...)

a function with variable number of arguments. printf identify number of arguments using const char string - it count number of % signs. It takes first argument after const char argument and walks down the stack. It occasionally happened that local variables are situated just under function frame. But on other compilers and with other directives you will get other results, because in this case behaviour is undefined. For example, on my computer I get 0, 100, 200. On win VSE I get 0..0..random number in debug mode and rand.. 0 .. rand in release mode, etc.

Ivan Ivanov
  • 2,076
  • 16
  • 33