Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function float argument takes different value inside the function

Tags:

c

function

I am sure I'm missing something obvious here but just can't figure out what it is. In my repository, I have a file called ddpoly_2.c which contains a function called "ddpoly2". I call this function from the main function in tst5.c. If you look at the code in tst5_2.c, I am assigning to x a value of 2, immediately printing it and then passing it to "ddpoly2" as the third argument (which is as per what the calling pattern should be like as far as I can tell). I then immediately print x from within the function "ddpoly2". What I see is the following:

x outside: 2.000000
x inside : 0.000000
nc: 2
nd: 3

You can see that x was 2.000000 just before the function was called but it became 0.0000000 once inside the function. I must be missing something overtly obvious here but can't figure out what it is.

P.S. I compile the code using the makefile in the same directory.

EDIT: Including relevant parts of code here.

Calling the function in tst5_2.c:

int main(int argc, char *argv[])
{
//Used to determine which section gets its results printed.

    float c[] = {1,1,1,0,0};
    int nc = 2;
    float x = 2.0;
    float pd[] = {0,0,0,0,0};
    int nd = 3;
    printf("x outside: %f\n",x);
    ddpoly2(c,nc,x,pd,nd);      
}

printing it inside the function ddpoly2:

#include <stdio.h>

void ddpoly2(float c[], int nc, float x, float pd[], int nd)
{
    int nnd, j, i;
    float cnst = 1.0;
    printf("x inside : %f\n",x);
    printf("nc: %d\n",nc);
    printf("nd: %d\n",nd);
}
like image 661
Rohit Pandey Avatar asked Feb 16 '26 22:02

Rohit Pandey


1 Answers

You're calling a function without a prototype. This is illegal since 1999 but your compiler is helpful and allows this as a compatibility with old C standards.

The C standard says:

If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double.

The correct solution is to:

  1. Always have correct function prototypes.
  2. Always enable all warnings in compilation and treat them as errors.
like image 112
Art Avatar answered Feb 19 '26 14:02

Art



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!