Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Output of C Programs | Set 16

  • Difficulty Level : Medium
  • Last Updated : 31 Jul, 2018

Predict the output of below C programs.

Question 1




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


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




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


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
Recommended Articles
Page :

Start Your Coding Journey Now!