0

I pass a float to a function expecting an int:

#include <stdio.h>
void p(int a){
  printf("%d\n",a);
}

int main(){
  float b;
  b=3.333f;
  p(b);
}

Is there a gcc compiler option which will warn about this mismatch? gcc -Wall does not raise warning.

5
  • 1
    -Wconversion does cause a warning in this case when using gcc as mentioned in one of the answers for the linked question. May 19, 2019 at 22:46
  • -Wconversion works. My question is different from the linked question (mine is about formal-actual parameter mismach, the linked question is a simple assignment conversion) although -Wconversion works for both situations.
    – Youjun Hu
    May 19, 2019 at 23:01
  • 1
    @YoujunHu matching of arguments to formal parameters is defined to behave like simple assignment
    – M.M
    May 19, 2019 at 23:04
  • @M.M I asked a new question (stackoverflow.com/questions/56212992/…) for the case that the function definition is in another file. For this case, -Wconversion does not help.
    – Youjun Hu
    May 20, 2019 at 0:12
  • @YoujunHu well that is an entirely different scenario
    – M.M
    May 20, 2019 at 0:50

1 Answer 1

1

Use -Wconversion to get a warning for implicit conversions:

#include <stdio.h>

void p(int a)
{
    printf("%d\n", a);
}

int main()
{
    float b = 3.333f;
    p(b);  // to get a warning for this implicit conversion, use -Wconversion
}
./example.c:11:7: warning: conversion from 'float' to 'int' may change value
                           [-Wfloat-conversion]
   11 |     p(b);
      |       ^

See Using the GNU Compiler Collection (GCC) - 3.8 Options to Request or Suppress Warnings

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.