Static variable re initialization:In the second part of the code i reinitialize the static variable x to 5. o/p of the first code is as expected but why o/p of the second part is 6 6 why not 6 7.
void foo()
{
static int x ;
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
//output will be 1 2
//But if i re initialize the static variable then why the output is like this:
void foo()
{
static int x ;
x=5;
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
//output is 66 why not 67
The result of:
x = 5;
x++;
is that x is 6. Since you execute this code twice you get the output 66.
Note, x = 5; is an assignment, not an initialization.
The output is 6, 6 because you reinitialize it to 5 each time you call the function.
To initialize it only once (and get 6, 7) you need to write:
static int x = 5;
Furthermore, the first code may yield unexpected results, because the variable is uninitialized and may contain any value.
The result is as expected because, in the function foo(),
void foo()
{
static int x ;
// what ever be the value of x until this point is retained.
// But what you are trying to do is assign the variable x again to 5, which means
// you are overwriting the previous value of x with 5.
x=5;
x++;
// Since x is always 5 due to overwriting, x++ will always yield "6" no matter what.
printf("%d", x);
}
In this scenario, the keyword static does not have any effect on the output.
void foo()
{
static int x ; // point 0
x=5; // point-1
x++; // point -2
printf("%d", x); // point- 3
}
int main()
{
foo(); // exe-1
foo(); // exe-2
return 0;
}
The program execution flow and the value of x at that point
Irrespective of how many times foo() is called, point-0 will be called only once.
exe-1: (point-0)x=0--> (point-1)x=5 (assigned) --> (point-2)x= 6
current value of x=6 before exe-2
exe-2: this time it doesn't comes to point-0, it comes to point-1, which is overwritting the current value of x(which is 6) with 5 again. So, after this, when it comes to point-2, the value of x is incremented from 5 to 6, so it prints 6
Related
#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:
First in print1 statement the value of the will increment by 5 , x will be 15 .
Then upon calling print1 function for the 2nd time it will be 15+5=20, since it will hold the previous value.
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.
for the last statement value of x will be 15+5=20.
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?
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.
int main() {
x=5;
printf("%d",x+3);
}
x could be either 5 or 8 after this example (I know that the output on the screen would be 8.)
The value at the address of x remains unchanged in this example. Inside the printf, we first get the value at the address of x and then add it to 3 and output it to the screen.
This is why we use statements like x=x+3 to change the value.
This kind of thing doesn't exist. What's best to do is to perform the operation outside of the printf() function:
#include <stdio.h>
int main() {
int x = 5;
x += 3; // x = x + 3
printf("%d\n", x);
}
According to Tomo Ceferin, x won't change because of the language's logic.
This works in C99. Not sure if any other version does.
#include <stdio.h>
int main() {
int x = 5;
printf("%d\n", x += 3);
}
Your program does not compile because there is no definition for x.
You should also include <stdio.h> to declare printf properly.
The statement printf("%d", x + 3); does produce 8 on standard output, but it does not modify the variable x, assuming x is defined as int x; somewhere.
You could modify x inside the call to printf: this has always been supported by the C language, although it is considered confusing.
#include <stdio.h>
int main() {
int x = 5;
printf("%d\n", x += 3); // prints 8 with a side effect
// x now has a value of 8
printf("%d\n", x); // prints 8 again
return 0;
}
The value of x remains the same, because you do not change it at all. Also, you should take into account to declare what type of data is your variable.
For example:
int main(){
int x = 5; //this is the variable x, declared as an integer. Its value is 5.
printf("%d", x + 3) //here you print an integer variable which has the value of (x+3),
//(5 + 3 = 8), to be more precise. (this instruction has nothing to
//do with the value of x, because you're not changing x in any way.)
}
So you will get on the screen the value of 8.
Hope it helped.
Can some one explain the execution of this program .
OUTPUT is:
1
2
3
4
3
2
1
how does function retain value 3,2,1 in the end
main(){
int h=0;
g(h);
}
g(int n){
n++;
printf("%d\n",n);
if (n ==4)return 88;
g(n);
printf("%d\n",n);
}
You are getting the above output because at the 8th line of your code you are calling the function agian recursively so the remaining code after the 8th line is saved in the call stack in your memory. So, when you get the output 1 2 3 4, the remaining code that is left (in call stack) is executed hence you are getting this output.
below is the call stack of your program
when n = 0 the stack will place 1
|___|
|___|
|_1_|
when n = 1 the stack will place 2
|___|
|_2_|
|_1_|
when n = 2 the stack will place 3
|_3_|
|_2_|
|_1_|
when n = 4 the stack will not place anything as it encounters the return statement
now, we have some values in our stack
so the program starts popping the top most value in stack (here n = 3) and continue the execution where it left off (i.e it will print the value) and this process will go on until the stack is empty.
NOTE: You can visit this video to understand more effectively about recursion https://www.youtube.com/watch?v=Mv9NEXX1VHc
g(int n){
n++;
printf("%d\n",n); // n=1 print 1 & call g(n) with 1 now g(1) make its own n=2 print 2 & call g(2)
//... print 3 & call g(3) becomes 4 print 4 return 88
if (n ==4)return 88;
g(n);
// now after the return we get back to the 3rd call that called g(3)
//so it print 3 at the end 3 ends
//we go back to the one that called g(2) so we print 2 at the end... & same for 1
printf("%d\n",n);
}
You can read above answers they are pretty good, but here is another way to get you head around it. Simplest answer is the same way that caller function retains its value when calling any function. For example if you have:
int main (void) {
int a = 5;
fun1 (a);
}
void fun1 (a) {
fun2 (a);
printf("%d\n", a); // output would be 5
}
void fun2 (int a) {
a+=1;
fun3 (a);
printf("%d\n", a);
}
void fun3 (int a) {
a+=1;
printf("%d\n", a);
}
So fun1 () would print out 5, fun2 () 6 and fun3() 7. Recursion function is similar to above from perspective of caller and called function, instead of calling function with different name it is calling the function with same name, or in other words it is calling itself.
Look at this code:
void recFun (int a) {
if (a > 6)
printf("%d\n", a);
recFun (a + 1);
printf("%d\n");
}
Some people when I was in school would rewrite above to following (on a piece of paper of course this would yell at you if you try to compile it):
void recFun (int a) {
recFun (a + 1);
printf("%d\n");
}
void recFun (int a) {
recFun (a + 1);
printf("%d\n");
}
void recFun (int a) {
printf("%d\n");
}
In C the function arguments acts as local variables inside the function. Further C uses call-by-value which means that the value of variable used by the caller as argument is copied to the functions argument variable. Consequently the two variables are completely independent variables.
Consider this code:
void foo(int x)
{
x++;
printf("%d", x);
}
void bar(int y)
{
y++;
printf("%d ", y);
foo(y);
printf("%d", y);
}
bar(0);
This will output "1 2 1"
Most people find that it's obvious that changes to x will not change y. They are by name two different variables. So no surprise in that.
If we change the code to use the same name for variables - like:
void foo(int x)
{
x++;
printf("%d", x);
}
void bar(int x)
{
x++;
printf("%d ", x);
foo(x);
printf("%d", x);
}
bar(0);
The output is still "1 2 1"
Simply because the variable x inside foo is another variable than x inside bar. The only relation ship they have is that x inside foo is initialized with a copy of the value of x inside bar. No matter what kind of change you make to x inside foo it will/can not change x inside bar.
Exactly the same goes for the recursion. Each function call creates its own variable n - completely independent of the n variable in previous calls.
Most implementations use a stack for implementing this functionality. Do a search for "stack frame" to get more information. Also see
Explain the concept of a stack frame in a nutshell
This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 years ago.
#include <stdio.h>
int main()
{
int x=100;
x=x++;
printf("x : %d\n",x); //prints 101
return 0;
}
What is the reason for output 101? I think output should be 100.
This is Undefined Behaviour, due to Sequence Points.
Between consecutive "sequence points" an object's value can be
modified only once by an expression
The end of the previous epxression x=100; is one sequence point, and the end of x=x++; is another.
Basically, your expression has no intermediate 'sequence points', yet you're modifying the value of X twice. the result of this is Undefined Behaviour: Basically, anything could happen: You could get 100, 101 or 42...
Here is what I believe you're looking for:
int main(){
int x=100;
printf("x : %d\n",x++); // Will print 100 and then increment x
return 0;
}
You're incrementing x before printing it - so this is the reason for the output 101.
You're doing the same operations as x = x; x++;
You're incrementing x after assigning it to x, effectively:
The x=x++ effectively becomes (assign x to x prior to increment) then (increment x)
This is going to give the same effect as if you were to wrote:
x = x;
++x; // Increment after the assignment
This should leave x as 101 after the x=x++; line.
You're incrementing the same x you're printing - here it doesn't matter whether post- or pre-incrementing.
x=x++ would produce the same result as x=++x.
If you would like to assign it another object do this:
#include<stdio.h>
int main(){
int x=100;
int y=x++;
printf("y : %d\n",y); //prints 100
printf("x : %d\n",x); //prints 101
return 0;
}
This is what is happening
#include <stdio.h>
int main()
{
int x=100;
x=x++; // This is original code however I have rewritten this as below
x=x;
x++;
printf("x : %d\n",x); //prints 101
return 0;
}
as you can see
x=x++;
can be rewritten as
x=x;
x++;
hence the result no surprises ...
The effect is that the value of x won't change.
x++ works like this:
Take a reference of the value.
Allocate a new integer and store the value into it.
Increment the reference.
Return the temporary integer.
In C++ it would look like this:
int PostIncrement(int& x)
{
int y = x;
x = x + 1;
return y;
}
The operator precedence is not lost in this way and the assignment is done after the increment.
int x=0;
int*a=&x;
void foo(int * a) {
static x=0;
x++;
printf("x's value %d ", x);
*a+=x;
a=&x;
*a=x+10;
}
int main(void) {
foo(a);
printf("a's value %d\n ", *a);
foo(a);
printf("a's value %d ", *a);
return 1;
}
I'm trying to analyze the above. First iteration of foo, when the function reaches to a=&x, the a after the function stops to get affected by what happens, since at the end of the function the pointer would go back to the original value he pointed to, now 1. the static x is now 1 as well. Second iteration: How's x got the value 12?! the static x became 2, and so I expected 3 to be the value of a.
The output is:
x's value 1 a's value 1
x's value 12 a's value 13
a=&x;
*a=x+10;
The above code adds 10 to x, because you set a to be a pointer to x, and then set the value pointed to by a to x+10.
The line a=&x makes a point to the static function-local variable x (since it's the innermost in scope). Thus *a=x+10 in the next line is equivalent to x=x+10, and x is 11 as we exit the function. At the next call, we increment x by 1, and it becomes 12.