Open In App

Output of C Program | Set 18

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Predict the output of following C programs.
Question 1 
 

C




#include<stdio.h>
int fun()
{
  static int num = 40;
  return num--;
}
  
int main()
{
  for(fun(); fun(); fun())
  {
    printf("%d ", fun());
  }
  getchar();
  return 0;
}


Output: 38 35 32 29 26 23 20 17 14 11 8 5 2
Since num is static in fun(), the old value of num is preserved for subsequent functions calls. Also, since the statement return num– is postfix, it returns the old value of num, and updates the value for next function call.
Question 2 
 

C




#include<stdio.h>
int main()
{
  char *s[] = { "knowledge","is","power"};
  char **p;
  p = s;
  printf("%s ", ++*p);
  printf("%s ", *p++);
  printf("%s ", ++*p);
  
  getchar();
  return 0;
}


Output: nowledge nowledge s
Let us consider the expression ++*p in first printf(). Since precedence of prefix ++ and * is same, associativity comes into picture. *p is evaluated first because both prefix ++ and * are right to left associative. When we increment *p by 1, it starts pointing to second character of “knowledge”. Therefore, the first printf statement prints “knowledge”.
Let us consider the expression *p++ in second printf() . Since precedence of postfix ++ is higher than *, p++ is evaluated first. And since it’s a postfix ++, old value of p is used in this expression. Therefore, second printf statement prints “knowledge”
In third printf statement, the new value of p (updated by second printf) is used, and third printf() prints “s”.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
 



Last Updated : 28 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads