+ 1
#define a function?
I was looking at the #define keyword and I wondered if it could be used on a function so I made this small bit of code: #include <iostream> using namespace std; #define int sumfunc(int x){return x;}; int main() { cout<<sumfunc(5); return 0; } my question is why does this work and am I actually defining sumfunc()?
9 ответов
+ 4
Hmm, this was a confusing one to figure out but I think I got it.
First of all you should realise that stuff like:
main(){ return 0; }
f(){ return 0; }
is allowed in C/C++. If a return type is missing the compiler assumes it returns an int. Although it's not a good practice to do.
When you do #define int sumfunc(int x){return x;} ( I removed the last ; as it doesn't matter in this case ) you literally replace all ints with that function. ( except that 1 int in the function parameter )
So int main(){} becomes
sumfunc(int x){return x;} main(){}
basically 2 functions on 1 line.
This is the place where your function gets defined.
This is also the reason why int main(){} seems to work but
int f(){}
int main(){}
doesn't. Because the function would be defined twice.
If you changed
#define int sumfunc(int x){ return x; }
to
#define double sumfunc(int x){ return x; }
then you suddenly get an undefined error. Because this time the int in main isn't replaced by the function and therefore there is no function definition. ( there is no double anywhere else in the code to replace )
So in short, don't do this, at least not with keywords.
#define a int sumfunc(int x){ return x; } is the one you want, where a is the name, not that this has much use though.
Lastly:
#define int sumfunc(int x){return x;}
int main()
{
int i = 0; // Can't use int anymore :(
}
+ 3
Yea, you're right swim, I spontaneously forgot that's a gcc thing during me figuring out what was going on and confused it since it is allowed in C.
+ 3
It seems this conversation is way beyond my level, i think ill go back to working with pointers and stuff until im good with them
+ 1
Dennis that was an interesting read, it's probably gonna take me a little while to fully understand whats going on here but anyways thanks for the in-depth explanation
+ 1
Dennis One more thing why doesn't it work when i try to make it a template function?
+ 1
Do you have the code that you used? Because it does work for me:
#define int template<typename T> somefunc(const T& x){ return x; }
or
#define int template<typename T> \
somefunc(const T& x){ return x; }
for multiline.
( still returns an int tho )
+ 1
Ah that explains it i didn't define the template