3

why I am getting 0.000000 as marks instead of 92.500000? Is there something to do with float in structures or something wrong in my code?

#include<stdio.h>

struct student
{
    char name[10];
    int age;
    int roll_no;
    float marks; 
};

int main()
{
    struct student s={"nick", 20, 52, 92.5};
    print(s.name,s.age,s.roll_no,s.marks);
}

void print(char name[],int age,int roll_no,float marks)
{
    printf("%s %d %d %f\n",name,age,roll_no,marks);//output:nick 20 52 0.000000
}
J...
  • 30,968
  • 6
  • 66
  • 143
Soujanya
  • 33
  • 5
  • 4
    Declare the function before you call it. And pay attention to compiler warnings. – interjay Aug 21 '21 at 12:44
  • Not directly related to your problem, but the whole point of using a `struct` is to make it more convenient to pass related information around as a bundle. So I would declare the `print()` function as taking one argument, either of type `struct student` or pointer to `struct student`. – Steve Summit Aug 21 '21 at 12:59
  • 1
    I'd like to emphasize - if you didn't see a compiler error then adjust your settings - the bad settings are causing you to waste time by running erroneous code – M.M Aug 22 '21 at 12:18

1 Answers1

3

The problem here is very subtle, but the compiler should be able to give you a warning about it (if not then you need to enable more warnings).

The problem is that you haven't declared the function print before you call it. That means the compiler will assume all numeric arguments have basic types, subject to the default argument promotions. This will lead to undefined behavior when you later define the function using different argument types.

You need to declare (or define) the function before you use it:

// Declare the function
void print(char name[], int age, int roll_no, float marks);

int main()
{
    struct student s={"nick", 20, 52, 92.5};
    print(s.name,s.age,s.roll_no,s.marks);
}

// Define (implement) the function
void print(char name[], int age, int roll_no, float marks)
{
    printf("%s %d %d %f\n", name, age, roll_no, marks);
}
Steve Summit
  • 45,437
  • 7
  • 70
  • 103
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    Good answer, but one correction: the compiler will assume that all arguments have *the types you actually passed*, and subject to the "usual argument corrections". Or, in this case, `int print(char*, int, int, double);` – Steve Summit Aug 21 '21 at 12:48
  • 1
    @SteveSummit: It is the *default argument promotions*, per C 2018 6.5.2.2 6. They perform the integer promotions and promote `float` to `double`. – Eric Postpischil Aug 21 '21 at 14:40