Like Tree1Likes
  • 1 Post By tabstop

Basic C program help

This is a discussion on Basic C program help within the C Programming forums, part of the General Programming Boards category; Hello everyone, IDE is Code::Blocks 10.05 When I compile the following Code: #include <stdio.h> int main () { int a ...

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    28

    Basic C program help

    Hello everyone,

    IDE is Code::Blocks 10.05

    When I compile the following

    Code:
    #include <stdio.h>
    
    int main ()
    
    {
        int a = 30 ;
    
        float b = 50.5 ;
    
        printf ("%i + %f = %i", a, b, a + b) ;
    
        getchar () ;
    
        return 0 ;
    
    }
    I get 0 as the result. How is that possible? I read that you can use
    expression instead of variables in the arguments which is what I did
    exactly. If I add one more variable for eg. int result = a + b
    and then instead of a+b i write result then I get the desired output
    i.e. 80

    Please help

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Because a+b is a float, it gets passed to printf as a floating-point value (specifically a double, by the magic of automatic promotion in function calls). But you told printf that it was an integer, so it grabs four bytes (instead of the eight that was probably given as a double) and interprets it as an int; and the four bytes it grabbed apparently was all 0.
    Bayint Naung likes this.

  3. #3
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Variadic function like printf() cannot help promote its argument.
    This is wrong.

    Code:
    printf(" %f \n", 3 );         // 3 is int. not promoted to float as format expects ....
    Now consider what's the type of a + b. a is int. b is float. Result of (a+b) type is float. see The C Book — Expressions and arithmetic

  4. #4
    Registered User
    Join Date
    Jul 2010
    Posts
    28
    Thanks guys that was quick and informative

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with basic program
    By brettski900 in forum C Programming
    Replies: 8
    Last Post: 03-03-2011, 02:57 PM
  2. Need help (Basic C++ program)
    By bamgolfing in forum C++ Programming
    Replies: 2
    Last Post: 11-16-2010, 08:27 PM
  3. basic program help
    By mouse666666 in forum C Programming
    Replies: 3
    Last Post: 09-16-2010, 01:36 AM
  4. Basic Program but I need Help
    By michigan353 in forum C++ Programming
    Replies: 10
    Last Post: 10-25-2005, 08:03 AM
  5. Basic Program but I need HELP
    By michigan353 in forum C Programming
    Replies: 2
    Last Post: 10-23-2005, 04:41 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21