int func (int,int);
int main ()
{
printf("hello");
}
Consider the above function. What is the purpose of defining functions like func? I have seen this repeatedly.
int func(int, int);
does not define a function, but declares it by providing its prototype. It's the "promise" to the compiler, that latest the linker will provide a module exposing such a function.
The prototype for a function covers its:
return type
name
the type and order of the arguments
The arguments' names are not relevant in the context of a declaration.
The function's arguments' names only need to be provided for the function's implementation, which might look like this:
int func(int a, int b)
{
return a + b;
}
On the other hand this
int func(int a, int)
{
return a;
}
is not valid.
The C Standard clearly states:
6.9.1/5 Function definitions
If the declarator includes a parameter type list, the declaration of each parameter shall
include an identifier, except for the special case of a parameter list consisting of a single
parameter of type void, in which case there shall not be an identifier. No declaration list
shall follow.
All the other answers are not answering the correct question explicitly, so I'm adding one here.
First of all, it's not a function definition because the body is missing. This semantic is called function declaration.
Before calling a function, the compiler needs to know what exactly the function is. This is named a "prototype". A prototype must be known before generating correct code to call a function. Consider this code:
// No previous info
int a = func(1, 3);
The compiler doesn't know if it is calling int func(int, int) or long func(char, double), nor can it perform error checking if the actual function is FILE* func(void*).
With a correct prototype privided, the compiler is able to perform necessary checking and generate the corresponding code of that function call.
It is not function defination but it is a functions declaration. A function declaration informs the compiler of the number of parameters the function has, the type of the function parameters and the type of the function return value.
1) It tells the return type of the data that the function will return.
2) It tells the number of arguments passed to the function.
3) It tells the data types of the each of the passed arguments.
4) Also it tells the order in which the arguments are passed to the
function.
5) It tells the name (identifier) of the function.
This is just a function declaration of a function to tell compiler that a function with name func exists having definition at end.
Consider this example:
#include<stdio.h>
int func (int,int);
int main()
{
printf("hello\n");
int c= func(5,4);
printf("%d\n",c);
}
int func(int a, int b)
{
return a+b;
}
Related
I just started learning C, and I came across this in one of the example given, I know this is a function prototype, but the concept I am yet to wrap my head around is the fact that does
void function(char *);
mean when I finally declare the function, it is going take an argument char pointer argument like so
void function(char *arg){}
?
Just to answer the question you gave:
What does “void fatal(char *);” mean?
This is the prototype/declaration of the function fatal.fatal is a function, which takes a pointer to char as one and only argument.
void is the return type of the function, which in this case mean that the function does not return a value to its caller or if it does, the value returned is interpreted as invalid by the caller.
The prototype/declaration of the function fatal() is important for the compiler. In this way, primarily the compiler will get "known", how the function is later used in the following program but secondary also checks if there are any inconsistencies between the definition, declaration and the use of the function.
In C, You may omit a specific identifier for the pointer to char in the declaration of the function, but not in the definition. This a circumstance where C is different as C++; In C++ it is permissible to omit the identifier also in the definition. You can look at the respective phrases in the standards in this answer.
So in the definition of fatal in C you have to provide an identifier for the char pointer:
// Definition of function fatal().
void fatal(char *a)
{
printf("The string of (a) is: %s\n",a);
}
but you can omit this one in the declaration:
void fatal(char *);
Note: The identifier between the provided arguments, when calling the function and the parameters specified in the declaration of the function may vary, like:
// Declaration (Protoype) of function fatal().
void fatal(char* a); // parameter a (pointer to char);
int main()
{
char b[] = "Hello"; // Declaration and Initialization of array b.
printf("Let´s use the function fatal to print what the string in b is
contained of!\n");
fatal(b); // when given as argument to a function, b
// is a pointer to the first element of the char
// array of b.
}
// Definition of function fatal().
void fatal(char* a)
{
printf("The string of (a) is: %s\n",a);
}
See more about the difference between parameters and arguments here: What's the difference between an argument and a parameter?
In the more far view, there is also an important difference between "pass by value" and "pass by reference". A pointer argument/parameter is always a pass by reference. What these two especially are and how they distinct is best explained here: What's the difference between passing by reference vs. passing by value?
In this context and the context of scope visibility, it is also important to know if you have f.e. an identifier x which refers to an object in the function fatal, the same identifier of x can be used in the caller, and vice versa, to refer to a total different object in each scope. - Means, you can have the same identifier (name) for different objects in different scopes but each identifier can only used once in its scope.
Here void function(char *); is a function prototype which is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body.
It gives information to the compiler that the function may later be used in the program.
It is not needed if the user-defined function is defined before the main() function.
does
[...] mean when I finally declare the function, it is going take an argument char pointer argument [...]
?
Yes, it does.
The important thing with the declaration of the function are the parameters' types. The parameters' names are not needed within the declaration
void function(char *);
but only within the function's definition
void function(char *arg)
{
}
.
It just informs the compiler what type parameters functions takes and what is the return type of it.
int main()
{
double x = foo(1,2);
}
void foo(double x)
{
printf("%f", x);
}
in this compiler does not know what parameters of the function foo are and how to pass them properly. Return type is also unknown. The compiler will assume they are int - which is not the truth in this case
https://godbolt.org/z/J8juc4
Is it necessary to declare function before using it? Does the compiler give an error if we don't use a function declaration and call it directly. Please answer according to standard C.
If yes then what does it mean that argument of type are converted to int and float to double if arguments to function are not defined?
In ANSI C, you do not have to declare a function prototype; however, it is a best practice to use them. The only reason the standard allows you to not use them is for backward compatibility with very old code.
If you do not have a prototype, and you call a function, the compiler will infer a prototype from the parameters you pass to the function. If you declare the function later in the same compilation unit, you'll get a compile error if the function's signature is different from what the compiler guessed.
Worse, if the function is in another compilation unit, there's no way to get a compilation error, since without a a prototype there's no way to check. In that case, if the compiler gets it wrong, you could get undefined behavior if the function call pushes different types on the stack than the function expects.
Convention is to always declare a prototype in a header file that has the same name as the source file containing the function.
With prototypes, the compiler can verify you are calling the function correctly (using the right number and type of parameters).
Without prototypes, it's possible to have this:
// file1.c
void doit(double d)
{
....
}
int sum(int a, int b, int c)
{
return a + b + c;
}
and this:
// file2.c
// In C, this is just a declaration and not a prototype
void doit();
int sum();
int main(int argc, char *argv[])
{
char idea[] = "use prototypes!";
// without the prototype, the compiler will pass a char *
// to a function that expects a double
doit(idea);
// and here without a prototype the compiler allows you to
// call a function that is expecting three argument with just
// one argument (in the calling function, args b and c will be
// random junk)
return sum(argc);
}
In C, you need to define everything before you use it. I think the idea is that it can compile everything in one pass, since it always has all of the information it needs by the time it gets to it.
I'm not sure what you're asking with the second part. If the function isn't defined, it just won't work.
The short answer: in C89/90 it is not necessary, in C99 it is necessary.
In C89/90 the function does not have to be declared in order to be called. For undeclared function the compiler will make an assumption about function return type (assumes int) and about function parameter types (will derive them from the argument types at the point of the call).
In C99 the function has to be previously declared in order to be called. Note, that even in C99 there's no requirement to provide a prototype for the function, only a declaration is needed, i.e. a non-prototype declaration is OK. This means that the compiler no longer has to make any assumptions about the function return type (since the declaration always specifies it explicitly), but it still might have to make assumptions about the function parameters (if the declaration is not a prototype).
The C99 standard in 6.5.2.2 "Function call" describes what happens in a function call expression, including if no prototype has been seen by the compiler for the function:
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. These are called the default argument
Later, it describes what happens if the function call expression doesn't match what how the function is actually defined:
If the function is defined with a type that is not compatible with the type (of the expression) pointed to by the expression that denotes the called function, the behavior is undefined.
Clearly, to help ensure correctness, using function prototypes is the right thing to do. Enough such that C++ made requiring function prototypes one of the 'breaking' changes with c.
#include<stdio.h>
int slogan();
int main()
{
slogan(slogan());
return 0;
}
int slogan()
{
printf("onlyme\n");
}
My doubt is, the slogan function has no argument list in its prototype, then how come it accepts the function call as its argument?
In c the empty parameter list does not mean function that takes no arguments. It means function with unspecified number of arguments
To declare a function that takes no arguments write :
int func(void);
Because in C,
int slogan();
declares a function without saying anything about its arguments. This is not a prototype declaration at all, it's an old-style K&R declaration. The prototype declaration for a function taking to arguments is
int slogan(void);
The former form exists for backward compability with pre-1989 C, when you couldn't provide argument information in the prototype at all.
Look at First answer here(and second)
The first answer will give you an Accurate explanation of a functions declaration
Section 6.11.6 Function declarators(K&R C)
The use of function declarators with empty parentheses (not
prototype-format parameter type declarators) is an obsolescent
feature.
I thought the difference is that declaration doesn't have parameter types...
Why does this work:
int fuc();
int fuc(int i) {
printf("%d", i);
return 0;
}
but this fails compiling:
int fuc();
int fuc(float f) {
printf("%f", f);
return 0;
}
with the message:
error: conflicting types for ‘fuc’. note: an argument type that has a default promotion can’t match an empty parameter name list declaration
A declaration:
int f();
...tells the compiler that some identifier (f, in this case) names a function, and tells it the return type of the function -- but does not specify the number or type(s) of parameter(s) that function is intended to receive.
A prototype:
int f(int, char);
...is otherwise similar, but also specifies the number/type of parameter(s) the function is intended to receive. If it takes no parameter, you use something like int f(void) to specify that (since leaving the parentheses empty is a declaration). A new-style function definition:
int f(int a, char b) {
// do stuff here...
}
...also acts as a prototype.
Without a prototype in scope, the compiler applies default promotions to arguments before calling the function. This means that any char or short is promoted to int, and any float is promoted to double. Therefore, if you declare (rather than prototype) a function, you do not want to specify any char, short or float parameter -- calling such a thing would/will give undefined behavior. With default flags, the compiler may well reject the code, since there's basically no way to use it correctly. You might be able to find some set of compiler flags that would get it to accept the code but it would be pretty pointless, since you can't use it anyway...
prototype = forward declaration, so you can use it before you tell the compiler what it does. It still has parameters, however.
Useful in a lot of respects!
The declaration int fuc(float); tells the compiler that there exists a function fuc which takes a float and returns an int.
The definition int fuc(float f) { /*...*/ } tells the compiler what fuc actually is and also provides the declaration as well.
The difference between a declaration and definition is the difference between saying that a size 6 blue hat exists and and handing someone a size 6 blue hat: the declaration says that there is such a thing, the definition says that this thing right here is the thing in question.
This question already has answers here:
Is there a difference between foo(void) and foo() in C++ or C?
(4 answers)
func() vs func(void) in C99
(4 answers)
Closed 5 years ago.
What is better: void foo() or void foo(void)?
With void it looks ugly and inconsistent, but I've been told that it is good. Is this true?
Edit: I know some old compilers do weird things, but if I'm using just GCC, is void foo() Ok? Will foo(bar); then be accepted?
void foo(void);
That is the correct way to say "no parameters" in C, and it also works in C++.
But:
void foo();
Means different things in C and C++! In C it means "could take any number of parameters of unknown types", and in C++ it means the same as foo(void).
Variable argument list functions are inherently un-typesafe and should be avoided where possible.
There are two ways for specifying parameters in C. One is using an identifier list, and the other is using a parameter type list. The identifier list can be omitted, but the type list can not. So, to say that one function takes no arguments in a function definition you do this with an (omitted) identifier list
void f() {
/* do something ... */
}
And this with a parameter type list:
void f(void) {
/* do something ... */
}
If in a parameter type list the only one parameter type is void (it must have no name then), then that means the function takes no arguments. But those two ways of defining a function have a difference regarding what they declare.
Identifier lists
The first defines that the function takes a specific number of arguments, but neither the count is communicated nor the types of what is needed - as with all function declarations that use identifier lists. So the caller has to know the types and the count precisely before-hand. So if the caller calls the function giving it some argument, the behavior is undefined. The stack could become corrupted for example, because the called function expects a different layout when it gains control.
Using identifier lists in function parameters is deprecated. It was used in old days and is still present in lots of production code. They can cause severe danger because of those argument promotions (if the promoted argument type do not match the parameter type of the function definition, behavior is undefined either!) and are much less safe, of course. So always use the void thingy for functions without parameters, in both only-declarations and definitions of functions.
Parameter type list
The second one defines that the function takes zero arguments and also communicates that - like with all cases where the function is declared using a parameter type list, which is called a prototype. If the caller calls the function and gives it some argument, that is an error and the compiler spits out an appropriate error.
The second way of declaring a function has plenty of benefits. One of course is that amount and types of parameters are checked. Another difference is that because the compiler knows the parameter types, it can apply implicit conversions of the arguments to the type of the parameters. If no parameter type list is present, that can't be done, and arguments are converted to promoted types (that is called the default argument promotion). char will become int, for example, while float will become double.
Composite type for functions
By the way, if a file contains both an omitted identifier list and a parameter type list, the parameter type list "wins". The type of the function at the end contains a prototype:
void f();
void f(int a) {
printf("%d", a);
}
// f has now a prototype.
That is because both declarations do not say anything contradictory. The second, however, had something to say in addition. Which is that one argument is accepted. The same can be done in reverse
void f(a)
int a;
{
printf("%d", a);
}
void f(int);
The first defines a function using an identifier list, while the second then provides a prototype for it, using a declaration containing a parameter type list.
void foo(void) is better because it explicitly says: no parameters allowed.
void foo() means you could (under some compilers) send parameters, at least if this is the declaration of your function rather than its definition.
C99 quotes
This answer aims to quote and explain the relevant parts of the C99 N1256 standard draft.
Definition of declarator
The term declarator will come up a lot, so let's understand it.
From the language grammar, we find that the following underline characters are declarators:
int f(int x, int y);
^^^^^^^^^^^^^^^
int f(int x, int y) { return x + y; }
^^^^^^^^^^^^^^^
int f();
^^^
int f(x, y) int x; int y; { return x + y; }
^^^^^^^
Declarators are part of both function declarations and definitions.
There are 2 types of declarators:
parameter type list
identifier list
Parameter type list
Declarations look like:
int f(int x, int y);
Definitions look like:
int f(int x, int y) { return x + y; }
It is called parameter type list because we must give the type of each parameter.
Identifier list
Definitions look like:
int f(x, y)
int x;
int y;
{ return x + y; }
Declarations look like:
int g();
We cannot declare a function with a non-empty identifier list:
int g(x, y);
because 6.7.5.3 "Function declarators (including prototypes)" says:
3 An identifier list in a function declarator that is not part of a definition of that function shall be empty.
It is called identifier list because we only give the identifiers x and y on f(x, y), types come after.
This is an older method, and shouldn't be used anymore. 6.11.6 Function declarators says:
1 The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.
and the Introduction explains what is an obsolescent feature:
Certain features are obsolescent, which means that they may be considered for
withdrawal in future revisions of this International Standard. They are retained because
of their widespread use, but their use in new implementations (for implementation
features) or new programs (for language [6.11] or library features [7.26]) is discouraged
f() vs f(void) for declarations
When you write just:
void f();
it is necessarily an identifier list declaration, because 6.7.5 "Declarators" says defines the grammar as:
direct-declarator:
[...]
direct-declarator ( parameter-type-list )
direct-declarator ( identifier-list_opt )
so only the identifier-list version can be empty because it is optional (_opt).
direct-declarator is the only grammar node that defines the parenthesis (...) part of the declarator.
So how do we disambiguate and use the better parameter type list without parameters? 6.7.5.3 Function declarators (including prototypes) says:
10 The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.
So:
void f(void);
is the way.
This is a magic syntax explicitly allowed, since we cannot use a void type argument in any other way:
void f(void v);
void f(int i, void);
void f(void, int);
What can happen if I use an f() declaration?
Maybe the code will compile just fine: 6.7.5.3 Function declarators (including prototypes):
14 The empty list in a function declarator that is not part of a
definition of that function specifies that no information about the number or types of the
parameters is supplied.
So you can get away with:
void f();
void f(int x) {}
Other times, UB can creep up (and if you are lucky the compiler will tell you), and you will have a hard time figuring out why:
void f();
void f(float x) {}
See: Why does an empty declaration work for definitions with int arguments but not for float arguments?
f() and f(void) for definitions
f() {}
vs
f(void) {}
are similar, but not identical.
6.7.5.3 Function declarators (including prototypes) says:
14 An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.
which looks similar to the description of f(void).
But still... it seems that:
int f() { return 0; }
int main(void) { f(1); }
is conforming undefined behavior, while:
int f(void) { return 0; }
int main(void) { f(1); }
is non conforming as discussed at: Why does gcc allow arguments to be passed to a function defined to be with no arguments?
TODO understand exactly why. Has to do with being a prototype or not. Define prototype.
Besides syntactical differences, many people also prefer using void function(void) for pracitical reasons:
If you're using the search function and want to find the implementation of the function, you can search for function(void), and it will return the prototype as well as the implementation.
If you omit the void, you have to search for function() and will therefore also find all function calls, making it more difficult to find the actual implementation.
In C++, there is no difference in main() and main(void).
But in C, main() will be called with any number of parameters.
Example:
main (){
main(10, "abc", 12.28);
// Works fine!
// It won't give the error. The code will compile successfully.
// (May cause a segmentation fault when run)
}
main(void) will be called without any parameters. If we try to pass it then this ends up leading to a compiler error.
Example:
main (void) {
main(10, "abc", 12.13);
// This throws "error: too many arguments to function ‘main’ "
}