PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 16, 2022

[FIXED] What is the different effect of assigning to vs. initialising static variables in a function?

 August 16, 2022     c, output     No comments   

Issue

#include <stdio.h> 

int print1(void)    
{    
    static int x= 10;

    x+=5;    
    return x;    
}

int print2(void)     
{    
    static int x;

    x = 10;    
    x+= 5;    
    return x;
}

int main()    
{    
    int x;    
    x = print1();    
    x+= print1();    
    x+= print2();     
    x+= print2();    
    printf("%d", x);    
    return 0;    
}

My solution:

  1. First in print1 statement the value of the will increment by 5 , x will be 15 .
  2. Then upon calling print1 function for the 2nd time it will be 15+5=20, since it will hold the previous value.
  3. Now for the function print2, it will again initialise the x value with 10, then increment it by 5. Value of x will be 15.
  4. for the last statement value of x will be 15+5=20.
  5. x=15+20+15+20=70

But the answer is 65. Please correct me where did I go wrong? I even wrote it in my compiler, it is giving output 65, but if change the position of x inside Print2 statement like static int x=10, it is giving different output?

Why this is happening?


Solution

The init of a static variable like static int x=10; only happens once per program execution. And that is not like a statement being executed, it is during setup of variables for the program.
The assignment statement x = 10; is executed each time the function is executed.
This means the two code versions you discuss are different and especially have different effects on variable values; which in turn explains the different output.



Answered By - Yunnosch
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing