-2

Hy! I learn #define in C. My program about the absolute value. I have 2 files: ft_abs.h:

#ifndef FT_ABS_H
# define FT_ABS_H

# define ABS(Value) ((Value < 0) ? (Value * (-1)) : (Value))

#endif

and main.c:

#include "ft_abs.h"
#include <stdio.h>
#include <string.h>

int     main(int argc, char **argv)
{
    printf("%s", ABS(argv[1]));
    return (0);
}

compile

gcc -o abs ft_abs.h main.c 

and...

In file included from main.c:2:0: main.c: In function ‘main’: ft_abs.h:16:41: error: invalid operands to binary * (have ‘char *’ and ‘int’) # define ABS(Value) ((Value < 0) ? (Value * (-1)) : (Value)) main.c:17:18: note: in expansion of macro ‘ABS’ printf("%s", ABS(argv[1]));

When I change (Value * (-1)) to (-Value) it is not work too (wrong type argument to unary minus). If I change (-Value) to (Value) all ok, but it is nonsense. How should I change the code to make it work (using define of course)?

1 Answers1

2

argv[1] is of type char *. It does not make any sense to calculate the absolute value. You probably want to transform the argument to an int type and then calculate the absolute value.

printf("%d", ABS(strtol(argv[1], NULL, 10)));

In addition you should always put parentheses around your arguments when writing macros.

#define ABS(Value) (((Value) < 0) ? ((Value) * (-1)) : (Value))
Osiris
  • 2,783
  • 9
  • 17