Given a function in C++ with arguments that are only types and have no identifiers,
void foo1(int, int, int){cout << "called foo1";}
I can call it as such:
int main() { foo1(10, 10, 10); }
Why is this a valid construct in C++? Is this just an idiosyncrasy of C++, or does this kind of declaration actually have some purpose? Can we actually access the arguments that have been passed in somehow? (This kind of method declaration will not work in Java.)
When a function has no arguments, it does not receive any data from the calling function. Similarly when it does not return a value, the calling function does not receive any data from the called function.
Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.
1: Function with no arguments and no return value Function with no argument means the called function does not receive any data from calling function and Function with no return value means calling function does not receive any data from the called function.
What should be passed in parameters when function does not require any parameters? Explanation: When we does not want to pass any argument to a function then we leave the parameters blank i.e. func() – function without any parameter. 10.
Consider a case where you are required to provide a function that meets the following prototype
void dostuff(int x, int y, int z);
And say you are operating in a 2D space and do not use z
inside your implementation. You can
void dostuff(int x, int y, int z) { // use x and y }
and just ignore z
, but the compiler will likely spot that you have defined but not used z
and warn you that you could be making a mistake. Instead you can
void dostuff(int x, int y, int ) { // use x and y }
and leave out the definition of z
. The compiler will accept and silently discard the third parameter because it knows you don't want it.
You do not want to simply turn off the warning because of errors like this
void dostuff(int x, int y, int z) { for (int z = 0; z < MAX; z++) { // use x and y and z, the local z. } }
Where a poorly-named loop index shadows the parameter z
. The caller's input is now ignored and this could have bad consequences. This error is often hard to spot with the mark 1 eyeball, especially if the local z
is buried somewhere deep in a complex function.
Anytime the compiler can pick off a possible bug in your code, take advantage. It means less work for you.
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