A small technical doubt in C Programming


A Small technical doubt

Reply if anyone knows

This is a small pgm,Compile in gcc and see the result

#include<stdio.h>
#include<math.h>
int main()
{
float a=0;
printf(“\n %f \n”,a*-1);
printf(“\n %f \n”,abs(a*-1));
return 0;
}

I got the result as follows

-0.000000

-0.000000

Why is it so?

, ,

6 Responses to A small technical doubt in C Programming

  1. TheAnand October 8, 2010 at 5:20 PM #

    i give up….anyone knows the answer?

  2. TheAnand October 8, 2010 at 10:41 PM #

    Here is your answer :)

    http://praseedp.blogspot.com/2010/10/cc-programming-riddle.html

    By Praseed sire, one of the active barcampers and someone who knows his code!

    • Sabin October 9, 2010 at 5:43 PM #

      The answer is very interesting..
      I think everyone should go through it..

  3. Praseed Pai October 9, 2010 at 6:57 AM #

    Here is why it is so @
    http://praseedp.blogspot.com/2010/10/cc-programming-riddle.html

  4. A C coder October 9, 2010 at 9:27 AM #

    Your code is broken in lots of ways. abs() is defined in stdlib.h, not math.h. In the first printf statement, you are passing an integer to a float specifier. And in the second, you are attempting to take the absolute value of a floating point value with abs(), whose argument is clearly defined in the library as int. Having said that, gcc is just broken. Here’s what a good compiler returns when attempting to compile this junk:

    $ cc t

    printf(“\n %f \n”,abs(a*-1));
    ………………^
    %CC-I-IMPLICITFUNC, In this statement, the identifier “abs” is implicitly declared as a function.
    at line number 7 in file MY_DISK:[000000]T.C;2

    printf(“\n %f \n”,abs(a*-1));
    ………………^
    %CC-W-OUTFLOATINT, In this statement, this argument to printf and conversion specifier “%f” combine integer and floating-point types. Behavior can be unpredictable.at line number 7 in file MY_DISK:[000000]T.C;2

    printf(“\n %f \n”,abs(a*-1));
    ………………….^
    %CC-I-INTRINSICCALL, In this statement, an apparent invocation of intrinsic function “abs”, argument number 1 is of type “double”, which is not consistent with the expected type “int”. It will be treated as an ordinary external call at line number 7 in file MY_DISK:[000000]T.C;2

    If you choose to ignore all these compilation issues, you deserve everything you get.

    • Sabin October 9, 2010 at 5:36 PM #

      Thank you friend….
      but why gcc is not giving any warning/error since I didn’t include stdlib.h .
      Also as in the first printf statement I got -0.0 while doing calculations, and this in turn led to many other complications such -0.0 is taken as negative in some situations.(only SOMETIMES, not always and I did tried to fix with and without abs() )…
      And one more thing I have to share with the readers is I made the mistake that, for float it is fabs() and not abs().

Leave a Reply


*