ABS (A) and abs (int)

I am confused by the difference between the two in xcode, ABS (A) and abs (int). Perhaps Cant did not find any explanation on the Internet. What should i use? I actually work on an accelerometer. Using ABS (A) and abs (int) gives me two different values. Using abs (int) will cause the inf value to appear at a time, while ABS (A) will give me a different value, but never inf. Thank!

http://www.switchonthecode.com/tutorials/iphone-tutorial-reading-the-accelerometer

+5
source share
5 answers

abs()runs on int, that is, abs(-10.123)returns 10, and abs()is a macro from NSObjCRuntime.hthat returns a value whose type is the type of the argument.

+16

ABS NSObjCRuntime.h:

#define ABS(a) ({typeof(a) _a = (a); _a < 0 ? -_a : _a; })

. abs, , protoype

int abs (int number)

int.

+6

ABS() , , - , ABS() - , , . , , .

+3

, ,

#include <stdio.h>
#define BAD_ABS(A) ((A)<0 ? (-(A)):(A))
int     afunc(){
    printf("afunc was called\n");
    return 1;
}
int     main(void){
    int     a;
    a = BAD_ABS(afunc());
    /* this has the result of:
    a = (afunc()<0) ? (-(afunc())) : (afunc());
    */
}

'afunc' , < 0 second, -A A.

NSObjCRuntime.h , , DIY , .

 #define BAD_ABS(a) ((a)<0 ? (-(a)) : (a))

, ,

#include <stdio.h>
#include <stdlib.h>
int main(void){
   short seeds[] = {1,2,3};
   int i;
   for(i=0;i<10000;i++) printf("%ld\n", BAD_ABS(jrand48(seeds)));
}

it has a 50-50 chance to return a negative number !!!

If, on the other hand, you want to use the stdlib abs () function, then you should warn that it will not work with long integers. In this case, you should use labs ().

0
source

We have two options for

#define ABS(a) ({typeof(a) _a = (a); _a < 0 ? -_a : _a; })

in Swift 2 use

Int32 abs(Int32) which has a return type Int32
T abs(T) which has a return type T where T is a generic type

I hope this works, thanks

-1
source

All Articles