LearnFrenzy
Sign in Take a free test

C Variables · Predict the Output · Question 11

Address of a static local across calls – output Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>

int *slot(void) {
    static int value;
    value++;
    return &value;
}

int main(void) {
    int *a = slot();
    int *b = slot();
    printf("%d %d\n", a == b, *a);
    return 0;
}
  • A 1 2 Correct
  • B 0 1
  • C 1 1
  • D 0 2
Correct Answer: Option A

There is only one value, at the same address for the whole program, so both pointers are equal. After two calls it holds 2. Returning its address is safe because its lifetime never ends.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links