Basic problem in C

Discussion in 'C' started by naiya, Jun 12, 2007.

  1. naiya

    naiya New Member

    Joined:
    Jun 11, 2007
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    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 a moderator: Jun 12, 2007
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    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.
     
  3. naiya

    naiya New Member

    Joined:
    Jun 11, 2007
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice