Kenny said:
Program:
#include <stdio.h>
int main(void)
{
int indiarocks = 2, j = 3;
char webeingood[80];
sprintf(webeingood,"indiarocks + j = %d",indiarocks+j);
j = 27;
puts(webeingood);
}
O/P is 5. Why?
Because you're using a C implementation that's broken.
The output should have been "indiarocks + j = 5\n"; since
that's not what you got, complain to the C vendor.
Oh, that *is* what you got? Well, why didn't you say
so? If you suffer a bad fall and fear you've broken your
right arm, do you tell the doctor it's your left great toe
that hurts? If you ever expect to get anywhere in writing,
reading, or using computer programs, Kenny, you need to
develop the ability to observe in detail and describe with
accuracy.
Now to your question -- the one you didn't quite ask, but
should have. The sprintf() call fills the initial portion
of webeingood[] with a string of characters determined by the
values of the sprintf() arguments at the time of the call.
At that time, indiarocks is equal to 2 and j is equal to 3,
so the third sprintf() argument is equal to 5 and sprintf()
places "indiarocks + j = 5" in webeingood[].
Subsequent changes to the value of j -- or of indiarocks,
for that matter -- don't change what's already been put into
webeingood[]. Like any other variable, webingood[] retains
the last value stored until you store a new one. (If you
write your weight on a slip of paper and then go on a three-
week feeding binge and gain twenty kilos, does the number
on the paper change automatically?) When you arrive at the
puts() call, webeingood[] still holds the string that sprintf()
deposited in it, and puts() outputs that string followed by a
newline.
Variables in C are not like "variables" in mathematics,
nor like "formulas" in spreadsheets. They're more like pieces
of paper: you can write things on them and read them back again,
you can erase what's written and write something new, but the
paper doesn't self-erase or self-rewrite.
(Pedantry warnings: Yes, I know about "volatile." Yes,
I know about "storage duration." Yes, I know Kenny should
return a value from main(), lest his implementation not yet
conform to C99. All such matters -- well, maybe except the
last -- are beyond Kenny's current knowledge, and anyone who
carps on them is doing him no favors.)