void foo(void) and void foo()
What is the difference between
void foo(void); and void foo(); ? I used to think they were the same but a long time ago somebody said they're not, and I don't remember why. Anyone know? |
It's the same...
Maybe asking to Dennis Ritchie.... :) |
Re: void foo(void) and void foo()
Quote:
C++ should bitch about the missing void :) A K&R compiler will accept both. Cheers, Tink P.S.: C++ is right ;) |
I've never had a compiler balk at an empty set of parentheses. It's widely assumed that:
void foo() takes no arguments. Using void foo(void) just makes it explicit that the function takes no arguments. But it's so common for a function to have no arguments that the first syntax is usually okay too. (Are there compilers that complain about this? g++ has never said anything to me about it :) ) Anyway, the result is the same no matter which you use, unless you have a compiler that for some reason assumes that foo() means a function that takes an int argument, or something. But yes, Tinkster is right - it is best to be absolutely explicit! Don't assume anything in programming. |
Actually, there is a HUGE difference between
Code:
void foo() Code:
void foo(void) |
"... any number of arbitrarily typed arguments ..."
So how would one access those parameters? Manually pop them backwards off the stack? |
lackluster: I wouldn't really know...and I'd shoot anybody I worked with who wrote code like that!
|
void foo(void);
and void foo(); They are different if they are function prototype. If they are function definitions, there is no difference. If you declare a function prototype with empty argument (without void), you can have one or more integer or any type of pointer arguments in your function definitions. For example, If this is your function prototype, void foo(); Then these are the valid function definitions. void foo(int i) void foo(int a, int b, int c) void foo(char* c, int b) etc.. But If you declare the function prototype "with void", your function definition must not have any arguments. Here is an example. <code> #include <stdio.h> void myFunction(); main() { int i = 3; char a = 'A'; printf("Address of i is "); myFunction(&i); printf("Value of i is "); myFunction(i); printf("Address of a is "); myFunction(&a); printf("Value of a is "); myFunction(a); return 0; } void myFunction(int a) { printf(" %d\n", a); } </code> In the above example, the "myFunction" function can be passed any type of data without casting. But If you change the function prototype with (int), you won't be able to compile unless you cast each different parameter type to integer type explicitly in the function call. The function prototype with (void) will not be compiled too. |
moeminhtun : that is very clear, thank you :)
|
You're welcome. :)
|
All times are GMT -5. The time now is 07:36 PM. |