I'm new in C++
I was using java before, I'm trying to call a function in c++ from a hearder file.
Here is my code:
sum.h
int sum(int a, int b);
cur_time.h
#ifndef CUR_TIME_H
#define CUR_TIME_H
clock_t clock(void);
#endif /* CUR_TIME_H */
main.cpp
#include <iostream>
#include "sum.h"
#include "cur_time.h"
int main ()
{
int x;
int y;
x = sum(3,4);
std::cout << x;
y = clock(void);
y = std::cout << y;
return 0;
}
So in main.cpp I try to display the elapsed time of my system with this function: clock_t clock(void);
When I run the project, I have this error:
main.cpp:13:13: error: expected primary-expression before ‘void’
main.cpp:14:3: error: ‘__ostream_type’ was not declared in this scope
If I run the code without calling the second function it works for sum.
You don't have to (and mustn't) use void in parentheses on calling a function.
assigning std::cout << y to y is meaningless here and gcc gave me this error:
error: invalid user-defined conversion from 'std::basic_ostream' to 'int' [-fpermissive]
Therefore, main.cpp should be like this:
#include <iostream>
#include "sum.h"
#include "cur_time.h"
int main ()
{
int x;
int y;
x = sum(3,4);
std::cout << x;
y = clock(); // remove void
std::cout << y; // remove y =
return 0;
}
Have you defined your sum(int, int) function in Sum.h?
Simply doing int sum(int a, int b); is not good enough, you need to define that function.
int sum(int x, int y) {return x+y;}
Let's take that first error message as a clue. I encounter it a LOT, in various forms, when I write C++ code.
main.cpp:13:13: error: expected primary-expression before ‘void’
The phrase "expected primary-expression" almost always means that you have A) forgotten something, or B) typed something weird or unexpected.
For example, you will get the same kind of error if you were to try cout << "Hello, " < "world!" << endl; In that case, I put a < where I should have put a <<. (Actual example from my code two days ago.)
In your case, the error message is screaming about void, which means that void or whatever precedes it is out of place. In your line y = clock(void);, we know that the preceding token ( is correct...we're calling a function after all. That must mean that void is mistyped or out of place. Obviously it isn't mistyped. If you drop it, your code works.
What's up with that? Well, unlike some languages, C++ can accept an empty arg list, so long as the function wasn't expecting any arguments. y = clock(); will properly call the function.
[BONUS: If you're trying to call a constructor without any arguments, leave off the parenthesis altogether in the call. It's just one of those weird exceptions.]
So, what about that second error? In general, you should try to fix only the error at the top of the list (unless you know for certain what the other(s) are about). Many times, one error causes other weirder errors to happen as well. To see what I mean, try leaving off a semicolon and check out the errors you get as a result. Fix that error and recompile. If the second error shows up again, THEN you address it.
In regards to your comment to MikeCAT, this is a separate issue, but I'll address it the same anyway. Your clock() function returns clock_t, but you are assigning it to y, which is of type int. It appears that clock_t is based on int, so you should be able to get away with it. However, it may be a good idea to switch y to type clock_t as well, and see if that resolves it.
Beyond that, it may have to do with how you're using clock, though I'm not an expert on that class. If you continue to have problems, create a new question. On StackOverflow, you want to stick to ONE problem in ONE question. :)
(See my comment to your question for some additional tips on surviving and thriving around here.)
Related
The cout statement in function call swap is not executing. Why?
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
cout << "Value Swapped" << endl;
}
int main() {
int x = 400, y = 100;
swap(x, y);
cout << "x = " << x << " y = " << y << endl;
return 0;
}
I have expected below output:
Value Swapped
x = 100 y = 400
But the output I have got is:
x = 100 y = 400
You're not seeing "Value swapped" because your swap function never gets called. Instead, you're calling std::swap<int>.
If you hadn't said using namespace std;, you'd have found out that your swap function is being passed integers, but was expecting pointers. Reason #1 not to use using namespace std; -- you can easily end up not calling what you think you are. :)
your function swap is expecting pointers as arguments, but you are passing integers. So instead of calling your function, it's calling the c++ swap function. To better understand this, change the function name 'swap' to any other name like 'swapp' and you'll see this error:
invalid conversion from int to int*
write swap(&x, &y) and you'll get your desired output
Consider choosing a unique enough identifier name such that there will not be a conflict with a namespace identifier (as in std::swap). If you can't choose the name of your identifier, put it inside of a namespace.
Secondly, if the compiler does not enforce the function declaration that you state, you should manually check to see that you passed the variables correctly (i.e., &x and &y instead of x and y).
using namespace std imports another equally named function from namespace std into global namespace, so you end up in having two overloads:
swap(int&, int&); // from std; actually a template instantiation
swap(int*, int*);
You call swap as
swap(x, y);
Now consider: Which are the types of x and y, are they pointers? So decide yourself, which overload will get called?
If you hadn't imported the second overload via using namespace std, which generally is considered bad practice anyway (well, you got a victim of the pitfalls of right away...), you would have ended up in a compilation error instead (integers aren't converted to pointers implicitly!).
To get your function called, you need to make pointers from:
swap(&x, &y);
// ^ ^
Actually, that would have worked even with the imported namespace (despite of being bad practice), as the imported overload is a template, yours an ordinary function, thus yours is considered the more specialised overload and thus will be preferred.
I have this code, which is giving me a single error that indicates two problems.
int healthyConst = 0;
int sickConst = 1;
int recoveredConst = 2;
GraphMatrix<int, double> graph (100);
for (int i = 0; i < sampleSize; i++)
{
if(std::rand() % 2 > 0.05) graph.setVertexInfo(i, sickConst); //Error
else graph.setVertexInfo(i, healthyConst);
}
The error is:
error: no matching function for call to GraphMatrix::setVertexInfo(int&, int*)
And the function in question is declared as follows in the source:
void GraphMatrix::setVertexInfo(int v, VertexObject& info)
First, i should not be a reference. This seems nonsensical to me, yet I can not fix this. If I try to outsmart the compiler and type for(int* i = 0...) the error now complains of setVertexInfo(int&*, int*), and I don't even understand what this means.
Second, sickConst is not a pointer. It is just an int. Now I realize the method, as written, accepts VertexObject&, not VertexObject, but *sickConst also causes the compiler to complain of invalid type argument of 'unary *'. I've also tried &sickConst, which the compiler not unexpectedly interprets as a pointer.
Also note, identical errors are thrown for the second line of the for loop, presumably for the same reasons.
The question is: why am I getting these errors, and how do I fix them?
You stated that your function declaration within the source is as follows:
void GraphMatrix::setVertexInfo(int v, VertexObject& info)
However in your for loop you are passing it a type of int. Either change your function declaration & definition to accept a type of int or change the type that you are passing to your function as a VertexObject.
EDIT: thanks for all the speedy responses, I have a much better understanding of this concept now. Also, I'll try to make my error messages more clear next time.
EDIT: updated with my newest code. the error happens on line 18. Also, I'm beginning to wonder if my latest issue has to do with the original class itself?
I'm trying to teach myself classes and objects in C++. I did it once by just declaring a void function, outputting something on the screen, calling the object in main and everything worked fine.
Now, I wanted to expand upon this and make a simple addition thing. However, I get a couple errors on Code Blocks:
error: invalid use of non-static member function 'int Addition::add(int, int)'
error: no matching function for call to 'Addition::add()'
Here's my code:
#include <iostream>
using namespace std;
class Addition {
public:
int add (int x, int y) {
int sum;
sum=x+y;
return sum;
}
};
int main()
{
int num1;
int num2;
int ans=addobj.add(num1,num2);
Addition addobj;
addobj.add(num1,num2);
cout<<"Enter the first number you want to add"<<endl;
cin>>num1;
cout<<"Enter the second number you want to add"<<endl;
cin>>num2;
cout<<"The sum is "<<ans<<endl;
}
One of the most important things, a developer should learn to do is to read compiler's messages. It's clear enough:
error: no matching function for call to 'Addition::add()'
Your function in your class is
int add (int x, int y)
it takes 2 arguments and you pass none:
addobj.add();
You have 2 options:
create and initialize x and y inside your main and pass them as arguments
make add without parameters, create x and y inside add's body, as their values are taken from user input.
In this case, as the function's name is add, I'd chose the first option:
declare int x, y; inside your main
read the user input inside the main (the part, where you use cin and cout)
pass the x and y as arguments to add like this: addobj.add( x, y );
store the result (if needed), like this: int result = addobj.add( x, y );
You declared a method add(int, int) that takes two integers as arguments; you have to supply those arguments when you call it. It would be nice to print the returned value, as well:
Addition addobj;
std::cout << addobj.add(1, 2) << std::endl;
Your add function takes two arguments, yet you call it with none, so no matching function could be found. You must call the function as it was declared, i.e.,
addobj.add(1, 2);
Your function takes two arguments and yet you call it without providing them. You need to provide the two integer arguments that your function requires. To be useful you should store the result too. Something like this
int a = 1;
int b = 2;
int result = addjobs.add(a,b);
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int e=0;
int b=0;
cout<<"Enter Exponent";
cin>>e;
cout<<"Enter Base";
cin>>b;
pow(e, b);
cout<<"Power:"<<e;
return 0;
}
void pow(int e, int b)
{
int t=1;
while(b==t)
{
e=e*b;
t++;
}
}
Here is the error I received:
ulaga.cpp|29|error: 'pow' was not declared in this scope
Can any one explain why this error occurred?
The C++ compiler parses through your code file sequentially in order. i.e. line 1 then line 2 then line 3... and so on. So by the time the compiler comes to the function call statement pow(e, b); in your main() function, it hasn't yet reached the definition of the function void pow(int e, int b) below the main() function and therefore gives you the error. There are two ways to solve this.
1) Move the definition of void pow(int e, int b) (and any other function that you plan to call from main()) above the main() function itself. This way the compiler has already parsed and is aware of your function before it reaches the pow(e, b); line in your main().
2) The other way is to use a forward declaration. This means adding the line void pow(int e, int b); before the main() function. This tells the compiler that the function given by the forward declaration (in this case void pow(int e, int b)) is defined in this code file but may be called before the definition code of the function in the file. This is a better method as you may have multiple functions in your file calling one another in different order and it may not be easy to rearrange their definitions to appear before they are called in a file. Here's a good read on Forward Declaration
You may also want to pass parameters by reference to your function to get the correct result. i.e. use void pow(int& e, int& b). This will cause the values modified in your pow() function to actually be applied to integers e and b and not just to their copies which will be thrown away after pow() is done executing. This link about passing arguments by reference in functions is pretty good at explaining this.
You need to forward declare the pow function. Like -
....
void pow(int e, int b);
int main()
....
There are few things wrong here. For example e is passed by value. So, e in main is different from that of pow.
pow(e, b);
cout<<"Power:"<<e; // This just prints the value taken from console
// And not the calculated power.
Either make pow function to return a value (or) pass e by reference.
This can easily be fixed by just importing #include <cmath> in the beginning of your code.
You need to use forward declaration of your function pow. Or just move it's definition above the main function.
I was getting a similar error but I just added it.
#include<cmath>
and the "pow" not declared error got resolved.
int& lameness()
{
int h=66;
return h;
}
int main()
{
int c;
c = lameness();
cout<<"c is "<<c<< endl;
system("pause");
return 0;
}
Why does this work? int h is a local variable and shouldnt h be destroy once it exits function scope?
If i change my function to this it works without warning. Is this safer in any way?
:
int& lameness()
{
int h=66;
int &a = h;
return a;
}
Yes. But the wonderful thing about undefined behavior is that what actually happens is... undefined. Destroying an int actually doesn't involve doing anything at all, so if nothing reuses that spot on the stack, the value is going to still be there. That's what makes this kind of thing so frustrating -- often it seems to work, until you make some small, seemingly unrelated change and it stops working!
It works by coincidence, check this:
http://www.velocityreviews.com/forums/t285367-return-reference-to-local-variable.html
Basically, it returned the right value due to the memory still being set to that value. Sometimes in the future, that might not be the case. Don't do this.
It does not work. It is undefined behavior. Your skepticism was right on: the lameness function is an error, and some compilers would flag it as such. Nonetheless, a compiler may be "conforming" and still "allow" this code...such is the "lameness" of C and C++.
It is destroyed. It happens to work because memory that h was stored in hasn't been overwritten by the time you print the value.
It only works for you by coincidence, and because your code takes a copy of the value in the reference before doing anything else. It is not guaranteed to work.
You could see it failing with:
#include <iostream>
using namespace std;
int& lameness()
{
int h=66;
return h;
}
int main()
{
int &c = lameness();
cout << "c is " << c << endl;
return 0;
}
Of course, I had to ignore compilation warnings:
x.cpp: In function ‘int& lameness()’:
x.cpp:5:13: warning: reference to local variable ‘h’ returned [enabled by default]
x.cpp: In function ‘int main()’:
x.cpp:12:28: warning: ‘h’ is used uninitialized in this function [-Wuninitialized]
The output was:
c is 0
This happens because by the time c is passed to the I/O system, the space that was once h in lameness() has been reused for other variables, thus scratching the 66 that was stored in the space. In fact, even your original code produces 0 on my machine.