Basic problem in C

naiya's Avatar
Go4Expert Member
If I write
Code:
void main()
{  
int x;
float y;
char z;
printf("\nx=%d",x);
printf("\ny=%d",y);
printf("\nz=%d",z);
getch();
}
OUTPUT:
x=-28852
y=0.000000
z=!!
But if I declare x,y and z in global declaration section then output comes
x=0
y=0.000000
z= (here comes cursor after one blankspace).
why?

Last edited by shabbir; 12Jun2007 at 22:54.. Reason: Code block - http://www.go4expert.com/forums/misc.php?do=bbcode#code
DaWei's Avatar, Join Date: Dec 2006
Team Leader
You've got several code problems and a posting problem. For the posting problem, read the "Before you make a query" thread and learn to put your code in tags to preserve its indentation/formatting. If you don't, we're not likely to read your future posts.

Now for the code: You have to give the variables you've declared a value. Declared inside main, they're local and will just contain junk until you assign a value to them. If you declare them globally, most compilers (not all) will initialize them to zero. You should still assign them a value of your own before printing them.

As for the printing, %d means int. %d will not print a float or a char properly. Use %f for floats, %c for chars. There are other formatting symbols for other types. Read the documentation on printf before you use it, for God's sake.
naiya's Avatar
Go4Expert Member
DaWei
I am sorry. The code was wrongly written by mistake. I know that %d means int, %f means float and %c means char.I will not make this kind of silly mistake in future.
Anyway, Thanks.