Thread: Easy scanf() question

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    30

    Easy scanf() question

    This code:
    Code:
    float x;
    scanf("%f", x);
    produces this warning:
    Code:
     warning: format â%fâ expects type âfloat *â, but argument 2 has type âdoubleâ
    ?I don't understand. I thought %f is for float, and x is a float?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You forgot the &. You need the address of the variable to be able to scan into it.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Roger View Post
    This code:
    Code:
    float x;
    scanf("%f", x);
    produces this warning:
    Code:
     warning: format â%fâ expects type âfloat *â, but argument 2 has type âdoubleâ
    ?I don't understand. I thought %f is for float, and x is a float?
    There are two things wrong, one with your code, one with the error message.

    First, the error message makes no sense. It says argument 2 is a "double" but it is clearly a float. The compiler is stupid.

    Second, you need to pass the ADDRESS of x, not x itself:

    Code:
    float x;
    scanf("%f", &x);
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  4. #4
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    It says argument 2 is a "double" but it is clearly a float. The compiler is stupid.
    Heh, I think this is being slightly unfair to the compiler. The float is being promoted to a double so the error message really isn't wrong (the function will be receiving a double); but of course whether the message makes sense depends on whether you think it should refer to the type of the variable you're passing, or the type that's actually being passed (I don't suppose there are many languages where that sentence actually makes sense.)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf question
    By panfilero in forum C Programming
    Replies: 1
    Last Post: 11-21-2005, 07:22 AM
  2. This is hopefully an extremely easy question...
    By rachaelvictoria in forum C Programming
    Replies: 2
    Last Post: 11-07-2005, 01:36 AM
  3. 4 easy question
    By Zeratulsdomain in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2005, 10:43 PM
  4. easy question about machine code
    By Jaguar in forum Tech Board
    Replies: 3
    Last Post: 10-07-2003, 09:11 AM
  5. Easy question, (should be) easy answer... ;-)
    By Unregistered in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 06-12-2002, 09:36 PM