Search code examples
cgcccompiler-errorsg++gnu

ternary operator compile error when using gcc but no issue using g++


I have been getting compile issues compiling this code using gcc :

#include <stdio.h>
#include <stdlib.h> /*srand, rand*/
#include <time.h> /*time*/
#include <math.h> /*sqrt*/

int abs(int x) {
 return( (x>0) ? x : int(-x));
};
int max(int x, int y) {
 return( (x>y) ? x : y);
};
int min(int x, int y) {
 return( (x>y) ? y : x);
};

with this compile instruction : gcc sqrtsumofsquares.c -o test

The resulting error I get is this :

sqrtsumofsquares.c: In function 'abs':
sqrtsumofsquares.c:7:22: error: expected expression before 'int'

However when I compile the same code with g++ sqrtsumofsquares.c -o test

The code compile with no issue.

The code itself and the use of ternary operator seems to be syntactically correct

What modifications can I do to compile this code on gcc ? As I have to use gcc and not g++


Solution

  • int(-x) is valid syntax in C++, but not valid syntax in C. I think you just meant to write -x.

    gcc compiles C code, and g++ compiles C++ code.

    In C++ int(something) casts a value to int, the same as (int)something