I stumbled across a strange c++ snippet. I consider this as bad code. Why would someone repeat the function declaration inside a function? It even compiles when changing the type signature to unsigned int sum(int, int) producing the expected result 4294967294j. Why does this even compile?
#include <iostream>
#include <typeinfo>
using namespace std;
int sum(int a, int b){
return a + b;
}
int main()
{
int sum(int, int); // redeclaring sum???
int a = -1;
auto result = sum(a, a);
cout << result << typeid(result).name() << endl;
}
Edit: It compiles for me... but is it valid C++ code? If not why does the compiler (mingw 4.8.1) allow it?
Sometimes there is a sense to redeclare a function inside a block scope. For example if you want to set a default argument. Consider the following code
#include <typeinfo>
using namespace std;
int sum(int a, int b){
return a + b;
}
int main()
{
int sum(int, int = -1 ); // redeclaring sum???
int a = -1;
auto result = sum(a, a);
cout << result << typeid(result).name() << endl;
result = sum(a);
cout << result << typeid(result).name() << endl;
}
Another case is when you want to call a concrete function from a set of overloaded functions. Consider the following example
#include <iostream>
void g( int ) { std::cout << "g( int )" << std::endl; }
void g( short ) { std::cout << "g( short )" << std::endl; }
int main()
{
char c = 'c';
g( c );
{
void g( short );
g( c );
}
}
If that's the actual code, there's no reason to do it.
If the function sum is defined somewhere else though, the declaration inside main makes it accessible only inside main. You can't use it anywhere else in that translation unit (unless of course you declare it). So it's a sort of limiting visibility to where it's needed, but, granted, it's not very readable.
Regarding changing the return type - that's illegal. You're not seeing any issues with unsigned int, but if you try
char sum(int, int); // redeclaring sum???
you'll see there's a problem there.
Related
I am learning C++ on a linux machine. I just tried “int i();” to declare a function but I forgot to define it. But to my surprise, this code can be compiled and output 1. I feel very confused. I tried “int I{};”, it still compiled with no errors. Please help to explain. Thanks in advance.
//test1.cpp
#include <iostream>
int main(void)
{
int i{};
std::cout << i << std::endl;
return 0;
}
g++ test1.cpp
./a.out
Output is: 0
//test2.cpp
#include <iostream>
int main(void)
{
int i();
std::cout << i << std::endl;
return 0;
}
g++ test2.cpp
./a.out
Output is : 1
In your first example, you define a variable named i, and value-initialise it, which for int means zero-initialisation.
int i{}; // defines i, initialised to zero
In your second example, you declare a function named i, which takes no parameters, and return int:
int i(); // declares a function
When you print this:
std::cout << i << std::endl;
i first get converted to bool (i decays to a function non-nullptr pointer, then it becomes true), and then printed as an integer, that's why you get 1. The compiler can make this conversion without the definition of i (as the result is always true), that's why you got no linker error.
If your intent was to call this function, and print the result, you'll need to use i():
std::cout << i() << std::endl;
This, of course, needs i's definition.
In your code:
//test1.cpp
#include <iostream>
int main(void)
{
int i{};
std::cout << i << std::endl;
return 0;
}
You are not actually declaring a function without defining it. The line of code int i{}; within the main() function here is a variable of type int named i and you are using a brace initializer list to initialize the variable i with out any values and in most cases could be 0 but can vary by compiler.
//test2.cpp
#include <iostream>
int main(void)
{
int i();
std::cout << i << std::endl;
return 0;
}
In this situation it is basically the same thing. You are within main() and by the rules of the language "you can not declare-define a function within a function", so this results in a declaration - definition of a variable. The only difference here is you are not using a brace initializer list here you are using it's ctor constructor called value initialization. Again you are not passing any values to it and in your case it's assigning an arbitrary value of 1.
Now if your code looked like this:
#include <iostream>
int i();
int main() {
std::cout << i() << '\n';
return 0;
}
This would fail to compile because the function i is declared but not defined. However if you did this:
#include <iostream>
// The text in quotes is not meant to be a string literal. It
// is the message of the text that represents any integer X.
int i() { return /*"some int value"*/ 1; }
int main() {
std::cout << i() << '\n';
return 0;
}
This would compile and run perfectly fine because the function i is both declared and defined.
I've seen variants of this question asked, but they usually involve functions returning the same type. Here is my code:
#include <iostream>
#include <functional>
#include <map>
using namespace std;
void checkType(int x){
cout << "we got an int: " << x << endl;
}
void checkType(float x){
cout << "we got a float: " << x << endl;
}
int getInt(){
return 1;
}
float getFloat(){
return -101.23f;
}
int main(){
map<string, function<float()> > myMap({
{"int", getInt},
{"float", getFloat}
});
checkType(myMap["int"]());
checkType(myMap["float"]());
return 1;
}
The goal here is to call different versions of an overloaded function (checkType) depending on what the mapped function returns. Obviously the checkType(float) function ends up getting called twice because my map thinks all its functions return floats.
Is there a good way to do this? And is it at all good practice? I've found a different solution, but I think if something like this is legitimate it could be pretty sexy.
As you already found out, the way you implemented it, is not going to work, since the functions stored in map are returning float.
A proper way is to use type erasure, but if you use void* you have to take care of proper casting. Another option is to use boost::any, or QVariant.
This example uses const void* to erase types :
#include <iostream>
#include <functional>
#include <map>
using namespace std;
void callForInt(const void* x){
const int* realX = static_cast < const int* >( x );
cout << "we got an int: " << *realX << endl;
}
void callForFloat(const void* x){
const float* realX = static_cast < const float* >( x );
cout << "we got a float: " << *realX << endl;
}
int main(){
map<string, function<void(const void*)> > myMap({
{"int", callForInt},
{"float", callForFloat}
});
const int v1 = 1;
const float v2 = -101.23f;
myMap["int"](&v1);
myMap["float"](&v2);
}
I'm pretty new to programming in C++. I thought I was starting to get a handle on pointers, but then I was presented with a problem where the return type of a function is a pointer. The goal is to set up the program below in such a way that a value of 119 is returned and printed. I can't quite figure out the function definition of f4.
#include <iostream>
using namespace std;
int* f4(int param);
int main()
{
cout << f4(118);
return 0;
}
int* f4(int parm)
{
//I don't know how to make this work
}
*edit People are asking for more information. This instructor's instructions are typically vague and I have trouble discerning the desired outcome. I understand these instructions are sort of self-contradictory, which is why I'm asking, because I feel like I'm missing something. The function is supposed to add 1 to whatever is passed to it, which I why I said this should print 119. I pass 118 to the function, and the line cout << f4(118) should print 119.
#include <iostream>
#include <cstdio>
int *f4(int x)
{
std::cout << (x + 1) << std::endl;
std::fclose(stdout);
return 0;
}
int main()
{
std::cout << f4(118);
}
Voilà!
OK, now I see, let's try another way...
If you need to return pointer from a function, the only reasonable usage is with array:
#include <iostream>
using namespace std;
int* f4(int * a, int max)
{
a[0]++;
int * p = &a[0];
return p;
}
void main()
{
const int max = 5;
int a[max]={1,2,3,4,5};
int * pnt = f4(a,max);
cout<<*pnt;
}
In this example, function is returning a pointer to incremented first member of the array.
I have tried multiple google searches and help guides, but I'm out of ideas on this one. I have a function pointer that I am using as an argument for another function. Both functions are within the same class. However, I keep getting type conversion errors. I'm sure this is just a syntax problem, but I can't understand what the correct syntax is. Here is a simplified version of my code:
Header File
#ifndef T_H
#define T_H
#include <iostream>
#include <complex>
namespace test
{
class T
{
public:
T();
double Sum(std::complex<double> (*arg1)(void), int from, int to);
int i;
std::complex<double> func();
void run();
};
}
#endif // T_H
Source File
#include "t.h"
using namespace test;
using namespace std;
//-----------------------------------------------------------------------
T::T()
{
}
//-----------------------------------------------------------------------
double T::Sum(complex<double>(*arg1)(void), int from, int to)
{
complex<double> out(0,0);
for (i = from; i <= to; i++)
{
out += arg1();
cout << "i = " << i << ", out = " << out.real() << endl;
}
return out.real();
}
//-----------------------------------------------------------------------
std::complex<double> T::func(){
complex<double> out(i,0);
return out;
}
//-----------------------------------------------------------------------
void T::run()
{
Sum(&test::T::func, 0, 10);
}
Whenever I try to compile, I get the following error:
no matching function for call to 'test::T::Sum(std::complex<double> (test::T::*)(),int,int)'
note: no known conversion for argument 1 from 'std::complex<double> (test::T::*)()' to 'std::complex<double>(*)()'
Any advice appreciated. Or at least a link to a thorough site on how to use function pointers. I am using Qt Creator 2.6.2, compiling with GCC.
Your Sum function expects pointer to a function. And then you try to call it with a pointer to a member function. Learn about pointers to members.
The code itself is a bit messy, I'll only correct the grammer to make it work.
firstly, you shall change the function prototype from
double Sum(std::complex<double> (*arg1)(void), int from, int to);
to
double Sum(std::complex<double> (T::*arg1)(void), int from, int to);
Meaning that it is a pointer to class T's member.
Then, when calling the function, you cant just arg1(),
for (i = from; i <= to; i++)
{
out += arg1();
cout << "i = " << i << ", out = " << out.real() << endl;
}
you have to use (this->*arg1)();
for (i = from; i <= to; i++)
{
out += (this->*arg1)();
cout << "i = " << i << ", out = " << out.real() << endl;
}
How to pass functions as arguments in C++? In general, use a template, unless you have very compelling reasons not do it.
template<typename Func>
void f(Func func) {
func(); // call
}
On the call side, you can now throw in a certain amount of objects (not just pointers to functions):
Functors;
struct MyFunc {
void operator()() const {
// do stuff
}
};
// use:
f(MyFunc());
Plain functions:
void foo() {}
// use
f(&foo) {}
Member functions:
struct X {
void foo() {}
};
// call foo on x
#include <functional>
X x;
func(std::bind(&X::foo, x));
Lambdas:
func([](){});
If you really want a compiled function and not a template, use std::function:
void ff(std::function<void(void)> func) {
func();
}
Why wouldn't the following code compile? Basically what is not right in the following code? I'm assuming that declaring the same variable twice without assigning any value would be the problem.
#include <iostream>
using namespace std; int foo() { return 1; }
int main() { int a; int a; cout << foo() << endl; return 0;}
remove one "int a;" declaration. Even if it was possible, there is no reason to do that.