Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
Is it possible for a c function to accept both double and long double arguments?

I have a function, mag, in a file mag.c that calculates the magnitude of an array.

#include <math.h>
#include "mag.h"

long double mag(long double arr[], int len){
    long double magnitude=0;
    for(int i=0;i<len;i++)
        magnitude+=pow(arr[i],2);
    magnitude=pow(magnitude,0.5);
    return magnitude;
}

I would like it to accept both double and long double arrays. I've read elsewhere (for instance here) that if an argument doesn't match the function declaration, it will be implicitly converted to the correct type. I wrote a function test.c to test this.

#include <math.h>
#include <stdio.h>
#include "mag.h"

int main(){
        double arr1[3]={0.0,1.1,2.2};
        printf("%Lf",mag(arr1,3));
        return 0;
}

However, this produced an error

test.c: In function ‘main’:
test.c:7:19: warning: passing argument 1 of ‘mag’ from incompatible pointer type [-Wincompatible-pointer-types]
  printf("%Lf",mag(arr1,3));
                   ^~~~
In file included from test.c:3:
mag.h:4:29: note: expected ‘long double *’ but argument is of type ‘double *’
 long double mag(long double arr[], int len);

Declaring the array as a long double allows the function to work properly. I also tried changing the argument type in the header file, but that returned -nan. Is there any easy way to make the mag function accept both double and long double arguments, or would it be simpler to make 2 separate functions? (If I need to make separate functions for double and long double arguments, I would need to do this for a lot of files.)

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

... it will be implicitly converted to the correct type. I wrote a function test.c to test this.

This works for some arguments like double converted to long double, but not double * converted to long double *.

C has _Generic just for this sort of programming. Use mag(arr, len) _Generic((arr) ... to steer selection of code.

I recommend to also use long double functions and long double constants with long double objects.

long double mag_long_double(const long double arr[], int len) {
  long double magnitude = 0;
  for (int i = 0; i < len; i++)
    magnitude += powl(arr[i], 2);  // powl
  magnitude = sqrtl(magnitude);
  return magnitude;
}

double mag_double(const double arr[], int len) {
  double magnitude = 0;
  for (int i = 0; i < len; i++)
    magnitude += pow(arr[i], 2);
  magnitude = sqrt(magnitude);
  return magnitude;
}

#define mag(arr, len) _Generic((arr), \
  long double *: mag_long_double, \
  double *: mag_double \
  )((arr), (len))

int main(void) {
  double arr1[3] = {0.0, 1.1, 2.2};
  printf("%f\n",mag(arr1,3));
  long double arr2[3] = {0.0, 3.3L, 4.4L}; // Add 'L'
  printf("%Lf\n",mag(arr2,3));
  return 0;
}

Output

2.459675
5.500000
over 4 years ago · Santiago Trujillo Relatório

0

You are correct that a function argument will be implicitly converted to the expected type, if possible. However, this implicit conversion will not go so far as to convert the object or the array that the function argument is pointing to. It will only convert the function argument itself (i.e. the pointer).

Therefore, in C, you will have to create two separate functions, or do something ugly, like creating a single function which takes a void * as an argument, which will be interpreted either as a long double * or a double * depending on the value of an additional argument:

#include <math.h>
#include <stdbool.h>

long double mag( void *arr, int len, bool is_long )
{
    long double magnitude=0;

    if ( is_long )
    {
        //interpret array as "long double"
        long double *arr_longdouble = arr;

        for( int i=0; i<len; i++ )
            magnitude += powl( arr_longdouble[i], 2 );
    }
    else
    {
        //interpret array as "double"
        double *arr_double = arr;

        for( int i=0; i<len; i++ )
            magnitude += powl( arr_double[i], 2 );
    }

    magnitude = powl( magnitude, 0.5 );
    return magnitude;
}

However, it is worth nothing that C++ (but not C) has the ideal solution for what you want to accomplish. In that language, you can make a single function template:

template <typename T>
T mag( T arr[], int len )
{
    T magnitude = 0;
    for( int i=0; i<len; i++ )
        magnitude += pow( arr[i], 2 );
    magnitude = pow( magnitude, 0.5 );
    return magnitude;
}

In this function, the data type T can be either a double or a long double (or any other data type, as long as the code compiles). The compiler will automatically create a double and/or a long double version of the function for you, as required.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda