-4

What happens in this code?

#include <stdio.h>

int main(){
    int e;
    printf("%d ", e);
    printf("%s", e);
    return 0;
}

Does e will have a) Garbage value? b) NULL

In GCC it shows garbage value and in g++ it shows 0 and NULL. Thanks!!

ufhfhf
  • 17
  • 5

3 Answers3

5

This program invokes undefined behavior. You are using wrong format specifier for int data type in second printf statement. Do not expect any good. Also note that e is not initialized and its value is indeterminate.

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

Both statements invoke undefined behavior because e object is not initialized so its value is indeterminate.

The second statement also has the wrong conversion specifier, %s specification requires a char * argument.

So as someone mentioned in the comments, the correct answer is neither a) nor b) but c) demons flying out your nose.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

This program when compiled generated warning:

warning: format ‘%s’ expects argument of type ‘char’, but argument 2 has type ‘int’ [-Wformat=] printf("%s", e);*

And in both cases it generates garbage values.

gcc :

enter image description here

g++ :

enter image description here

Pratyush Khare
  • 689
  • 5
  • 16