Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I tried to execute the following code on code blocks, where instead of getting the marks as 92.5 I get 0.000000

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
}
like image 551
Soujanya Avatar asked Jan 19 '26 22:01

Soujanya


1 Answers

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);
}
like image 105
Some programmer dude Avatar answered Jan 22 '26 11:01

Some programmer dude



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!