#include <stdio.h>
int main()
struct books
{
char title[50];
char author[50];
char sub[100];
int b_id;
};
//here int main should be used but not still the code runs fine why??
{
struct books b1={"48lop","rg","sh",288017};
printf("%s\n",b1.title);
printf("%s\n",b1.author);
printf("%s\n",b1.sub);
printf("%d",b1.b_id);
return 0;
}
CodePudding user response:
It's because you are using k&r syntax.
You do not use ANSI C syntax.
CodePudding user response:
Originally in C, the way functions were defined was:
int MyFunction(a, b, c) // List of parameter names here. No declarations, just names.
int a; // Declarations of parameter types here.
float b;
char c;
{
… // Body of function here.
}
A problem with this is that function declarations, like int MyFunction(a, b, c);
, do not specify the types of the parameters. This hinders the compiler from checking that a call is passing correct types of arguments. To improve the situation, the modern style was introduced, where the parameter types are declared inside the parentheses of the function declarator (int MyFunction(int a, float b, char c)
).
The way you wrote your code fits the old style. int main()
has no parameter declarations. It does have a list of parameter names, but the list is empty. Then, after int main()
, it has a declaration. That is a declaration of a structure type—it declares only the type, as in struct foo {int x;};
. It does not declare an actual structure of that type, as in struct foo {int x;} MyFoo;
. The declarations between a function declarator and the function body are supposed to declare the parameters of the function. Having one that declares just a type and not a parameter violates a constraint in the C standard, but your compiler seems to be tolerant and to allow this declaration (probably with a warning message) because, although it does not declare a parameter of the function, it also does not declare any other object (just a type).
There is no reason to use this old form of function declaration in new code. Compilers still accept it only so that old code (very old code) can still be compiled.
CodePudding user response:
This is because your compiler rearranges your code. If you check the assembly code generated from your c code, you'll see what your compiler does.