Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Basic problem in C (http://www.go4expert.com/forums/basic-c-t4649/)

naiya 12Jun2007 21:14

Basic problem in C
 
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?

DaWei 12Jun2007 22:49

Re: Basic problem in C
 
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 13Jun2007 12:46

Re: Basic problem in C
 
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.


All times are GMT +5.5. The time now is 09:07.