Error after variable used as a function parameter in C? - c++

Can I use a variable as a function parameter after creating the variable while creating the function in C++ or another programming languages?
For example something like below. The code gets error but I wonder if it is possible to do this:
#include <iostream>
using namespace std;
int a = 0;
int dondur(a){
return a;
}
int main(int argc, char **argv)
{
int b=20;
cout << dondur(b);
return 0;
}

Up to the fact, that your function should read
int dondur(int a){
return a;
}
this is legal. The parameter 'int a' hides the global variable. The expected output is therefore 20 and the global variable a=0 remains unchanged.

Related

How to access function defined in namespace in other .cc file

I have a file named test.cc
#include <stdio.h>
int doit(){
return 4;
}
namespace abc {
int returnIt(int a){
return a;
}
}
I can use doit(), but how can I use this function in namespace in my main.cc without using .h file:
using namespace abc;
int doit();
int main(int argc, const char * argv[]) {
cout<<returnIt(3)<<endl; // print 3
cout<<doit(); // print 4
return 0;
}
You can call functions by first declaring them. Example:
namespace abc {
int returnIt(int a); // function declaration
}
int main() {
abc::returnIt(3); // the declared function can now be called
Note that the declaration must be exactly the same as used elsewhere in the program. To achieve identical declarations across translation units, it is conventional to put the declaration into a separate file (called a header) and include that file using the pre-processor whenever the declaration is needed.
All you need is to simply write the functions before the main function. That way, the compiler has processed the function prototypes by the time it encounters them in main and can validate the function call.
int doit()
{
return 4;
}
int returnIt(int a)
{
return a;
}
int main(int argc, const char * argv[])
{
cout<<returnIt(3)<<endl; // print 3
cout<<doit(); // print 4
return 0;
}
In general, avoid using namespace;. It makes for code that can be broken or be rendered less readable due to incorrect variable/function usage. That is because too many symbols can occupy the same (global) scope.
If another library needs to used, as user4581301 pointed out, then it may be simpler to use eerorika answer/method.

usage on c++ function pointer

I'm a newbie to C++, learning pointer of function recently, a little confused by usage of pointer of function;
I practiced the following code:
#include <iostream>
#include <sstream>
using namespace std;
int subtraction(int a,int b){
return a-b;
}
int main(int argc, const char * argv[])
{
int (*minus)(int,int)=subtraction;
cout<<minus(5,4);
return 0;
}
it works well;
so,I try a little variation:
#include <iostream>
#include <sstream>
using namespace std;
int subtraction(int a,int b){
return a-b;
}
int main(int argc, const char * argv[])
{
int *minus(int,int)=subtraction;//only here different!
cout<<minus(5,4);
return 0;
}
I practiced it in Xcode on Mac,it give me Error:
Illegal initializer (only variables can be initialized)
but I think compiler can recognized the two is same,why must have a pair of parenthesizes?
In your original code
int (*minus)(int,int)=subtraction;
declares minus as a function pointer that takes parameter int, int and returns int.
In your second code
int *minus(int,int)=subtraction;
declares minus as a function that takes parameter int, int and returns a pointer int *.
You can use a function name(which is automatically converted to a function pointer) to initialize a function pointer, but you can't initialize a function.
This is a matter of operator precedence. The function call operator () has a higher precedence than the dereference operator *. So you must use parentheses to specify the correct order of evaluation.
int *minus(int, int)
means: First call a function named minus, then dereference the return value (int* in this case).
int (*minus)(int, int)
means: First dereference "minus", which returns a function, and then call that function.
You have tagged your code C++ and using iostream so I can safely assume you are looking for a C++ solution.
In such scenario, its best to use class template std::function instead of the function pointer syntax that is prone to error.
#include <iostream>
#include <sstream>
#include <functional>
int subtraction(int a,int b){
return a-b;
}
int main(int argc, const char * argv[])
{
std::function<int(int,int)> minus = subtraction;
//int (*minus)(int,int)=subtraction;
std::cout<<minus(5,4);
return 0;
}
Alternatively, if you would still want to continue with pointer to function, typedefs are recommended
#include <iostream>
int subtraction(int a,int b){
return a-b;
}
typedef int (*MINUS)(int,int);
int main(int argc, const char * argv[])
{
MINUS minus = subtraction;
//int (*minus)(int,int)=subtraction;
std::cout<<minus(5,4);
return 0;
}
And finally, another widely used option is to use functors.
#include <iostream>
struct MINUS
{
int operator()(int a,int b){
return a-b;
}
};
int main(int argc, const char * argv[])
{
//int (*minus)(int,int)=subtraction;
MINUS minus;
std::cout<<minus(5,4);
return 0;
}

Re-declaration error when using a prior variable in anonymous instance creation

g++ gives a re-declaration error when using previously declared variable in anonymous instance creation.
I have the following code in my "weird.cpp" source file:
#include <iostream>
int main()
{
int i = 0;
int j = int ( i );
int ( i );
}
The error i am getting is,
weird.cpp: In function ‘int main()’:
weird.cpp:7: error: redeclaration of ‘int i’
weird.cpp:5: error: ‘int i’ previously declared here
I have tried this in mac and linux with versions 4.2 and 4.7 respectively. I have also tried with other types instead of int. The result is the same error. Can anyone help me understand this problem? Thanks.
First of all, the parentheses you're using here don't do anything.
int i = 0;
int j = int(i); // This is casting i to an int. It's already an int.
int j = i; // This does the same as the last line.
int (i); // This is redeclaring an int named i, which had already been done.
int i; // This is the same as the last line.
What you are saying about an object accepting an int in it's constructor doesn't make sense.
struct A { A(int) {} };
int i;
A obj(i); // A instance named obj which takes integer i as constructor argument.
I don't really understand what you're trying to achieve here, perhaps this?
int i = 0;
int j = i;
{
int i; // In another scope, shadowing the first i for scope duration.
}
You could be forgiven for being confused by this, it's a case of C++'s context-sensitive nature and how that is interpreted by the compiler.
int (i);
is being treated as a declaration of "i" (and since you already have a variable called i in this scope and have not enabled -Wno-shadow, it's not allowing this).
Contrast with the following case, which doesn't compile: (see http://ideone.com/QuwnTC)
#include <iostream>
class Bark {
public:
Bark(const char* msg, const char*) {
std::cout << "Hear ye, hear ye. " << msg << std::endl;
}
};
void bark(const char* i) {
Bark (i); // error here.
}
int main(int argc, const char* argv) {
bark("wtf");
}
It complains that Bark (i) shadows "i"s declaration.
However, both of the following DO compile: http://ideone.com/dcGMET
void bark(const char* i) {
Bark (i + 1);
}
or having two arguments inside the parenthesis: (http://ideone.com/tMzSY9)
#include <iostream>
class Bark {
public:
Bark(const char* msg, const char*) {
std::cout << "Hear ye, hear ye. " << msg << std::endl;
}
};
void bark(const char* i) {
Bark (i, NULL);
}
int main(int argc, const char* argv) {
bark("wtf");
}
Clearly, the treatment of "type (name)" here is some sort of special case, and you might want to raise this with the compiler developers.

Constructing Objects and Calling Member functions

Here is my code
#include <iostream>
using namespace std;
class MyTestClass
{
int MyTestIVar;
public:
MyTestClass(void);
int firstCallMethod(void);
int secondCallMethod(void);
};
MyTestClass::MyTestClass(void)
{
MyTestIVar = 4;
}
int MyTestClass::firstCallMethod(void)
{
return secondCallMethod();
}
int MyTestClass::secondCallMethod(void)
{
return MyTestIVar;
}
int main(int argc, char *argv[])
{
MyTestClass mTC;
cout << mTC.firstCallMethod() << endl;
return 0;
}
If use use
MyTestClass mTC();
instead it will disallow me to call any member functions and display this error
./experiment.cpp: In function ‘int main(int, char**)’:
./experiment.cpp:31:14: error: request for member ‘firstCallMethod’ in
‘mTC’, which is of non-class type ‘MyTestClass()’
I read the posts on value-initialize etc, but this error still doesn't seem logical to me. Why would this affect member functions?
And help greatly appreciated :-)
MyTestClass mTC();
Does not declare an object of the MyTestClass class, as you think.
It Actually, declares a function by the name of mTC which does not take any parameters and returns an MyTestClass object.
This is known as the Most Vexing Parse in c++.
You have stumbled upon the most vexing parse.
The line
MyTestClass mTC();
is parsed as a function prototype of a function named mTC which has no arguments and returns an instance of MyTestClass.

error in c++ main file int expression

I am making a new program in c++ i get the current error
expected primary-expression before ‘int’
about this line
p1::pascals_triangle(int depth);
My code is:
this is my functions.cpp
using namespace std;
/**
* Note the namespace qualifier used here - I did not bring 'p1' in
* scope, therefore we need the "p1::" to preceed the function definitions.
*/
void p1::pascals_triangle(int depth) {
// Implement problem 1 in here.
this is main
using namespace std;
int main(int argc, char *argv[]) {
// Need to implement argument processing here
// If you want to set a function pointer, you just take the
// address of the function ('&' means 'take address of'):
double (*pf)(double k); // declares the function pointer
pf = &p1::test_function;//test_function; // sets the value of 'pf' to the address of the 'p1::test_function' functio\
n.
p1::pascals_triangle(int depth);
Unless you're declaring a method, you probably don't need the keyword "int".
#include <iostream>
namespace foo {
void pascals_triangle(int depth) {
std::cout << depth << std::endl;
}
int another_method(int y);
}
using namespace std;
int
foo::another_method(int y) {
cout << "called another_method with " << y << endl;
return 8;
}
int main(void) {
int x = 5;
foo::pascals_triangle(x);
foo::another_method(x + 1);
return 0;
}
If I were to write instead:
int main(void) {
int x = 5;
foo::pascals_triangle(int x);
foo::another_method(x + 1);
return 0;
}
I'd get:
In function ‘int main()’:
error: expected primary-expression before ‘int’
p1 needs to be an existing namespace or class name.
If that does not solve the problem you will have to give some surrounding code to make sense of your question ;)
Good luck.