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
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With