Output of C Programs | Set 16

Predict the output of below C programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
  
char* fun()
{
  return "awake";
}
int main()
{
  printf("%s",fun()+ printf("I see you"));
  getchar();
  return 0;
}

chevron_right


Output: Some string starting with “I see you”
Explanation: (Thanks to Venki for suggesting this solution)
The function fun() returns pointer to char. Apart from printing string “I see you”, printf() function returns number of characters it printed(i.e. 9). The expression [fun()+ printf(“I see you”)] can be boiled down to [“awake” + 9] which is nothing but base address of string literal “awake” displaced by 9 characters. Hence, the expression [“awake” + 9] returns junk data when printed via %s specifier till it finds ‘\0’.



Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
  
int main()
{
  unsigned i ;
  for( i = 0 ; i < 4 ; ++i )
  {
    fprintf( stdout , "i = %d\n" , ("11213141") ) ;
  }
  
  getchar();
  return 0 ;
}

chevron_right


Output: Prints different output on different machines.
Explanation: (Thanks to Venki for suggesting this solution)
The format specifier is %d, converts the base address of string “11213141” as an integer. The base address of string depends on memory allocation by the compiler. The for loop prints same address four times. Try to use C++ streams, you will see power of type system.

Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above



My Personal Notes arrow_drop_up


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.