How can a variable in C++be named a function call? - c++

While going through some allegro tutorials I found an odd call.
int al_init();
The function al_init() initializes allegro so that the allegro functions can be used. What is with the int al_init(); line? If I change this line of the code to exclude int it works the same, but if I take out the line altogether it does not work. What is this line doing? The only thing I can imagine is that it creates an integer and assigns it the return value of the al_init() function, with that likely being -1 for failure and 0 for success etc. But if that is what this is doing, then how can you even check the return value?

In C/C++ there are function declarations and function definitions:
Declarations look like these:
int a_function();
void another_function();
double yet_another_function();
Explanation:
The identifier before the function name (e.g. int, void, double) describes the type of value returned by the function.
If you do not specify one, it defaults to int (which is why it works when you remove int from int al_init(), but not when you remove the declaration altogether)
void means it's not supposed to return a value (even though technically it can, but that's for rarer cases)
Definitions look like these:
int a_function() {
std::cout << "hello world!";
int x = 1;
int y = 2;
return (x + y);
}
Notice the difference:
Declarations end with ;
Definitions are followed by a block of code enclosed by braces: { and }, but no ;!
In some cases, you do not need to declare a function. If it's at a point in the code where the definition has already been seen, the definition can substitute for the declaration (this leads us to the next point...)
The purpose of declaration is to tell the program that, for example, there is a function named a_function, it expects no arguments, and it returns a value of type int.

Are you sure you aren't looking at the function declaration?

According to C's syntactic rules, a prototype is defined as:
<return-type> function-name (param1, param2, ..);
And a function call is defined as:
function-name(param1, param2,...);. So its obviously defining a function prototype and NOT calling the function.
C89 and previous rules were:
With the above rule, another rule was:
For implicit integer return type, the prototype was suppose to be defined outside of any executable function code. If it was inside of a function, it would be called a function-call and not function-prototype-definition.
That aside, lets start with the question:
While going through some allegro tutorials I found an odd call. int
al_init();
That's incorrect, it looks like a function prototype or declaration
The function al_init() initializes allegro so that the allegro
functions can be used. What is with the int al_init(); line? If I
change this line of the code to exclude int it works the same, but if
I take out the line altogether it does not work.
What does not work? Stops to compile? That would be obvious because it will not be able to find al_init() function. Also the reason it works without the "int" is because its implicitly assumed to return an integer.
What is this line doing?
Its telling the compiler that al_init() library function is defined elsewhere, typically in a .lib or .a or .dll, and you would want to use it in your program.
The only thing I can imagine is that it creates an integer and assigns
it the return value of the al_init() function,
Absolutely incorrect interpretation of code, it does not create any integer, nor assigns any value to it.
with that likely being -1 for failure and 0 for success etc. But if
that is what this is doing, then how can you even check the return
value?
Since you want to know what that function returned, you could do this while an actual call to al_init():
int retval = al_init();
printf("al_init() returned %d",retval);

Related

In C++ Output Parameter vs Return Value

What is/are the difference(s) between output parameters and return values? I've looked everywhere and I can't seem to find a simple definition for either.
The return value is something well defined in C++; for instance, x in return x; is the return value, whereas int in the function declaration int myfunc() is the return type.
The concpet of output paramters is not defined in C++. However someone would interpret it as either of the following:
function parameters passed by non-const reference, as long as you actually modify it in the function, otherwise why would you call it output? An example is x in the following function declaration: void myfunc(int& x);
function parameters passed by (not necessarily const) pointer to non-const, like x in both the following function declarations: void fun1(int * x) and void fun2(int * const x);
concerning this latter case, it allows "encoding" a missing parameter in as a nullptr default value, as in void fun3(int * x = nullptr).
A first difference is aesthetic: which one you like the most?
Another one is that the former concept and syntax help you convey the message that the function is giving back a value, something which is clear at the call site too (whereas at the call site you might not know if a parameter corresponding to an argument is passed by reference or not).
There are several differences between this two ways a function can have "consequences" at the caller site. For instance, you can only have one return value, whereas you can have as many paramters as you like.
Performancewise, complier optimizations can minimize the difference in performance, and maybe you should not worry (yet) about it.

C/C++ - how is (void) used not as a parameter? [duplicate]

This question already has answers here:
in c: func(void) vs. func() [duplicate]
(2 answers)
Closed 9 years ago.
I have seen some code in C/C++ that goes like this:
void Main(void)
And
int Main(void)
What is the reasoning for this: why is it not a parameter but used in parentheses after the void/int e.t.c name?
void in a parameter list is effectively a keyword, not specifying the type of anything. The reason for its existence is purely historical.
Early C did not have function prototypes or any syntax for parameter lists. A function definition would look like this:
foo()
int x; // These are the parameters.
float y;
{
return x + (int) y;
}
There was "no need" for prototypes because the compiler would assume every call passed exactly the correct type and number of arguments. This was error-prone. Furthermore the return type was assumed to be int, which is an even more brittle assumption. The first prototypes specified only the return type.
float foo(); // Still no parameters.
When the familiar float foo( int x, float y ) syntax was introduced, backward compatibility with the preceding style was retained. The void keyword was used to differentiate between an indeterminate (missing) parameter list and an empty parameter list.
In C, float foo() and float foo( void ) mean different things to this day.
In C++, indeterminate parameter lists are unsupported, and float foo( void ) is a discouraged, but not deprecated, synonym for float foo().
Furthermore C++ allows templates to determine the type of an argument, but generating a (void) parameter list by a template is an error.
In C (void) means that there is no arguments required in function call, while () means unspecified number of arguments. In C++. () means the same as (void)
Here is what C standard says
5.1.2.1 Freestanding environment
In a freestanding environment (in which C program execution may take
place without any benefit of an operating system), the name and type
of the function called at program startup are implementation-defined.
/ .. / The effect of program termination in a freestanding environment
is implementation-defined.
5.1.2.2 Hosted environment
A hosted environment need not be provided, but shall conform to the
following specifications if present.
5.1.2.2.1 Program startup
The function called at program startup is named main. The
implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any
names may be used, as they are local to the function in which they are
declared):
int main(int argc, char* argv[]) { /* ... */ }
In C this
void func() {
}
means a function that takes an indeterminate number of arguments. If you want to write a function that takes zero arguments you do this
void func(void) {
}
The reasons for this are in the history of the C language, they don't make much sense otherwise. For this reason C++ changed the rules. In C++ the first example above means a function that takes zero arguments, and this
void func(int x, ...) {
}
means a function that takes a variable number of arguments (one or more in this case). C will also accept this.
So in C and C++, example 2 means zero arguments and example 3 means a variable number of arguments, but C and C++ disagree on what example 1 means, for C it's an indeterminate number of arguments, for C++ it's zero arguments.
If you see (void) in a C++ program it's either code that has been ported from C and no-one has bothered to change it, or it's code which is expected to be compiled as both C and C++ (in a header file for instance).
Draft n1570;
5.1.2.2.1 Program startup:
The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv.....)
It is clear from the C standard that void is used for a function having no parameter.
In c++, sometimes parameter "names" may be excluded if they are not called from within the function. If you know that you will use it, you may add the parameter name by yourself. It would hardly make sense for the void parameter of main, though.
In old compilers it was mandate to specify void in parenthesis in case main is not going to accept any parameters. but these days you may need to use like only:
void main()

Why does casting a function to a function type that is identical except for return type fail? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is the return type part of the function signature?
Following up on a related but tangential question ( How to disambiguate function templates that differ only by return type? ), I would like to ask a question related to the fact that the return type of a function is not considered to be part of the signature of a function.
Consider the following code:
#include <iostream>
int foo()
{
return 0;
}
int main()
{
long n = static_cast<long(&)()>(foo)(); // Error: incorrect return type
int p = static_cast<int(&)()>(foo)(); // Compiles just fine
}
The line of code noted above results in a compilation error, because the return type of the function type to which foo is being cast does not match the return type of the function foo.
But I thought the return type of a function does not play a role in the signature of the function!
According to a certain line of thinking, since the function signature long(&)() matches the signature of foo, the cast of foo to a function of this type should succeed.
However, the cast does not succeed. Where does the reasoning go wrong? If the cast cannot fail due to the function signature, then why does the cast fail?
You're correct that the return type doesn't form part the signature of the function.
However, it does form part of the type of the function, and you're not allowed to convert pointers to incompatible function types.
The return type is part of the type, although not used for overload resolution. It is important not to confuse the terms. Basically, the type includes arguments and return value, but during overload resolution, the return type is not considered. The type of the function or function pointer is a contract between the caller and the callee, and they must fully agree on the terms.
From a practical point of view, consider what would happen if what you suggest was allowed. Imagine a calling convention in which the caller reserves space and passes a pointer to that space to the function, the function will then construct in that location the returned object (this is actually a very common calling convention). Consider now that you were allowed to perform the cast you proposed and the following use case
static_assert(sizeof(T1)<sizeof(T2));
T2 f();
T1 (*p)() = &f;
p(); // call
Now when the compiler is processing p() it reserves space somewhere, and given the type of the function it needs to reserve sizeof(T1). It then calls the function, which ends up calling f which writes sizeof(T2) bytes into the location causing an overflow.
Even if the sizes matched, the code would be problematic. Consider T1==int and T2==float in a platform where sizeof(int)==sizeof(float). While the code above would not cause a buffer overrun, the bitpattern stored in the location of the return type would be that of a float, not that of an int.
The return type of a function is not part of the signature, but the signature isn't what the compiler needs to know in order to correctly call the function referred to by a function pointer or reference.
As well as the parameters, the compiler needs to know the return type, so that it can make space for the return value on the stack, or read the return value from the correct register(s), or whatever the calling convention demands in a given implementation.
That is why the return type is part of the type of the function -- so that the type tells the compiler what it needs to know at compile time in order to emit code to call the function.
the function signature long(&)() matches the signature of foo
long(&)() isn't a function signature, it's a type. foo(void) is a (representation of a) function signature. It includes the name and parameters. But you never need to specify a function signature in C++ code (well, perhaps as a string passed to dlsym or similar). The definitive representation of a function signature is the mangled name of the function in a given implementation. The mangling scheme isn't standard, it's up to the implementation (although if different implementations want to call into each other's libraries then they must use the same scheme, so the OS might specify one).
The return type of a function is considered part of its signature (and of its type). However, it is allowed to assign function pointers to variables with different return types if the return types are "covariant".

If void() does not return a value, why do we use it?

void f() means that f returns nothing. If void returns nothing, then why we use it? What is the main purpose of void?
When C was invented the convention was that, if you didn't specify the return type, the compiler automatically inferred that you wanted to return an int (and the same holds for parameters).
But often you write functions that do stuff and don't need to return anything (think e.g. about a function that just prints something on the screen); for this reason, it was decided that, to specify that you don't want to return anything at all, you have to use the void keyword as "return type".
Keep in mind that void serves also other purposes; in particular:
if you specify it as the list of parameters to a functions, it means that the function takes no parameters; this was needed in C, because a function declaration without parameters meant to the compiler that the parameter list was simply left unspecified. In C++ this is no longer needed, since an empty parameters list means that no parameter is allowed for the function;
void also has an important role in pointers; void * (and its variations) means "pointer to something left unspecified". This is useful if you have to write functions that must store/pass pointers around without actually using them (only at the end, to actually use the pointer, a cast to the appropriate type is needed).
also, a cast to (void) is often used to mark a value as deliberately unused, suppressing compiler warnings.
int somefunction(int a, int b, int c)
{
(void)c; // c is reserved for future usage, kill the "unused parameter" warning
return a+b;
}
This question has to do with the history of the language: C++ borrowed from C, and C used to implicitly type everything untyped as int (as it turned out, it was a horrible idea). This included functions that were intended as procedures (recall that the difference between functions and procedures is that function invocations are expressions, while procedure invocations are statements). If I recall it correctly from reading the early C books, programmers used to patch this shortcoming with a #define:
#define void int
This convention has later been adopted in the C standard, and the void keyword has been introduced to denote functions that are intended as procedures. This was very helpful, because the compiler could now check if your code is using a return value from a function that wasn't intended to return anything, and to warn you about functions that should return but let the control run off the end instead.
In imperative programming languages such as C, C++, Java, etc., functions and methods of type void are used for their side effects. They do not produce a meaningful value to return, but they influence the program state in one of many possible ways. E.g., the exit function in C returns no value, but it has the side effect of aborting the application. Another example, a C++ class may have a void method that changes the value of its instance variables.
void() means return nothing.
void doesn't mean nothing. void is a type to represent nothing. That is a subtle difference : the representation is still required, even though it represents nothing.
This type is used as function's return type which returns nothing. This is also used to represent generic data, when it is used as void*. So it sounds amusing that while void represents nothing, void* represents everything!
Because sometimes you dont need a return value. That's why we use it.
If you didn't have void, how would you tell the compiler that a function doesn't return a value?
Cause consider some situations where you may have to do some calculation on global variables and put results in global variable or you want to print something depending on arguments , etc.. In these situations you can use the method which dont return value.. i.e.. void
Here's an example function:
struct SVeryBigStruct
{
// a lot of data here
};
SVeryBigStruct foo()
{
SVeryBigStruct bar;
// calculate something here
return bar;
}
And now here's another function:
void foo2(SVeryBigStruct& bar) // or SVeryBigStruct* pBar
{
bar.member1 = ...
bar.member2 = ...
}
The second function is faster, it doesn't have to copy whole struct.
probably to tell the compiler " you dont need to push and pop all cpu-registers!"
Sometimes it can be used to print something, rather than to return it. See http://en.wikipedia.org/wiki/Mutator_method#C_example for examples
Functions are not required to return a value. To tell the compiler that a function does not return a value, a return type of void is used.

function concept

void execute(int &x,int y=100)
{
x=x+y;
cout<<x<<endl;
}
void main()
{
int a=5,b=6;
execute(b);
}
will the following program work in spite of not assigning a default value to the x(formal parameters in the function prototype).
Yes, it will work. By not assigning the default value to x you are forcing the caller to pass a value as the parameter. When you do execute(b) in main you are binding the reference x with actual parameter 'b' and since you have not passed any value to variable 'y' the default value will be used.
Firstly, there's no such thing as "function prototype" in C++. "Prototype" is a term from C parlance, which has no meaningful application in C++. What you have here is a function declaration, which also happens to be a function definition.
Secondly, it appears you are asking whether it is required to specify default arguments for all function arguments in C++, right? If so, the answer is no, there's no requirement to specify default arguments for all function arguments.
Thirdly, it is supposed to be int main, not void main.
You run execute(b), meaning that execute will run b = b + 100 (y is 100 since you didn't pass it in, and it got the default value), print out 106 and b will be modified back in main, since it's taken by reference.
I think you're confused as to how a function works. You're passing the value for x into it (well, a reference to an int not the actual value) so ... yes, that works.
By providing a default value for y ( int y=100 ) you're making it so the function can be called without passing the second argument to it. If called with a single argument, y will be assigned the value 100.
int a=5,b=6;
execute(b);
Once inside execute(), the initial value of x is 6, and y is 100.