【问题标题】:ternary operator compile error when using gcc but no issue using g++使用 gcc 时三元运算符编译错误,但使用 g++ 没有问题
【发布时间】:2021-07-07 16:47:57
【问题描述】:

我在使用 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);
};

使用此编译指令:gcc sqrtsumofsquares.c -o test

我得到的错误是这样的:

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

但是,当我使用 g++ sqrtsumofsquares.c -o test 编译相同的代码时

代码编译没有问题。

代码本身和三元运算符的使用似乎在语法上是正确的

我可以做哪些修改来编译 gcc 上的代码?因为我必须使用gcc 而不是g++

【问题讨论】:

  • int(-x) 是 C++ 中引入的函数转换,但在 C 中无效。问题不在于三元运算符,而在于函数转换。
  • 为什么您认为首先需要将-x 转换为int?已经是int
  • 与问题无关,但函数体在关闭}后不需要;

标签: c gcc compiler-errors g++ gnu


【解决方案1】:

int(-x) 在 C++ 中是有效的语法,但在 C 中是无效的语法。我想你只是想写 -x

gcc 编译 C 代码,g++ 编译 C++ 代码。

在 C++ 中,int(something) 将值强制转换为 int,与 (int)something 相同

【讨论】:

    猜你喜欢
    • 2012-12-18
    • 2017-05-12
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 2012-05-03
    • 2019-05-31
    • 1970-01-01
    相关资源
    最近更新 更多