Is this function well declared? - c++

this is my first question. I'm really new to programming and I'm struggling when it comes to discerning from well structured code from WTF codemonkey code. Is there anything I should have done different when creating this ubber simple program? My main concern is regarding the function.
#include <iostream>
using namespace std;
void enter_numbers ( int & iNum1, int & iNum2 ) {
cout << "Enter first number" << endl;
cin >> iNum1;
cout << "Enter second number" << endl;
cin >> iNum2;
}
float calc_avg ( int iNum1, int iNum2){
float fRes;
fRes =(float)(iNum1 + iNum2)/2;
return fRes;
}
void show_avg ( float fRes ) {
cout << "Average is: " << fRes;
}
void main () {
int iNum1;
int iNum2;
enter_numbers ( iNum1, iNum2);
float fRes = calc_avg (iNum1, iNum2);
show_avg ( fRes );
fflush(stdin);
getchar ();
}

You should not fflush an input stream, as described here: http://www.gidnetwork.com/b-57.html
Your main function should have int as return type and return 0, for successful execution:
What should main() return in C and C++?
In rest, your code seems fine. Note that for a beginner you should be happy, it is pretty good as it is. I just mentioned a few improvements you may want to made and pointed some sources for further documentation, as i guess you want to learn more.

Every corporate culture - or any other group of people working on code together - is going to have a set of coding style guidelines, variable and function naming conventions, and so on and so forth. There are going to be a vast plethora of opinions you'll hear (probably really soon =D) about how to make code readable, and the following issues are mostly religious:
Hungarian notation (variable names like lpctszName) vs plain English. My opinion is that there's a time and a place for it. Look up "Apps Hungarian" vs "Systems Hungarian".
Indentation. We all agree (pretty much - dissenters?) that the bodies of a compound statement (e.g. function definitions) should be indented. So do that. However, there are really heated debates about which line the brace goes on. I like the opening brace at the end of the line. Look up "One true indent style".
ReadableVariable vs readableVariable vs readable_variable and so on.
The bottom line is that, like any other body of text, code has an audience. It's the people you're working with, or who take over maintenance of your code, or who test it. In personal projects, it's you, some weeks down the road when you don't remember what variables were what. Your coding style should be consistent with what that audience knows.
Other than that, if there are no exceptions or compile-time errors, your code is good. In the future, working code goes on the code review StackExchange, though, and conceptual questions go to the programmers StackExchange. Welcome to StackOverflow =D.

Just write num1, num2, res and not iNum1, iNum2, fRes.
The type is already visible as part of the declaration.

Related

Namespaced Functions interfering with print

I'm new to the site and browsed several similar sounding questions but haven't found my exact problem. I suspect I'm making elementary mistakes. A link to an answer would be appreciated, or an explanation, and again I'm sorry if my question doesn't even match the title of the post.
For c++ on the Cxxdroid app for android and in Visual Studio C++:
I'm trying to experiment with classes and namespaces to provide flexible utility to the class. I want to use different implementations of the same function for personal analysis of certain algorithms on data structures; namely arrays vs lists/trees and also between recursive and iterative implementations of standard procedures. I know how to do asymptotic analysis but my stubborn mind wants real numbers.
Unfortunately, however, I can't even seem to get namespace functions to work without blowing up normal functionality. Please note, I haven't learned c++ formally yet because I'm exploring ahead of my introductory c/c++ course.
For example:
#include <iostream>
namespace iterative{
int power(int base,int expo){...}
}
namespace recursive{
int power(int base,int expo){...}
}
int main(int argc,char* argv[]){
int result = 0;
int num = 3;
int exp = 2;
//Expecting 9 in result
std::cout << "This prints fine" << std::endl;
result = iterative::power(num,exp);
std::cout << result;
std::cout << " This number and text doesn't print" << std::endl;
return 1;
}
I had a much more complex function with classes above the namespaced functions (search function for node classes inside a list/tree class) but it never worked. Then I just threw together the above snippet and tried to print result but the std::cout never fired after my function call.
Can anyone offer insight into what I'm doing wrong here? The first cout prints and the second wont. Further, execution hangs during the function call; the solution keeps running until I force it to stop.
I've tried to comment out one of the namespaces while using the other.
I've tried the using keyword with the namespace_name.
I've tried passing integers without variable usage: result = power(3,2);
I've tried printing the function result directly: std::cout << power(3,2) << std::endl;
I can't seem to get it to work on either application. I know this seems like a silly and simple question but after about a week of browsing the internet I'm inundated with very vague answers to questions regarding syntax. Perhaps I'm just not connecting the dots to my own problem...
Is my syntax in definition wrong?
Is my syntax in calling the function wrong?
Is my syntax in variable assignment wrong?
I'm at my wits' end.
Edit:
Now I feel really stupid.
You were correct. I didn't increment my variable in the iterative implementation, which meant it hung up on an infinite loop. I had to print the loop to see the numbers spitting out like I'm Neo in The Matrix. Unfortunately, I didn't test the recursive function because it felt dangerous to do so if I couldn't even get the iterative function to call first...
I was so focused on using namespaces for the first time that I never looked at the loop properly.
Thank you, and sorry for the bother. I'm going to try to extend this experiment to namespace-defining class member functions now.
Edit2: Feel free to delete this...unless it's felt that my stupidity can help others.
Silly mistake was made:
...
int power(int base,int expo){
int i = 0;
int retval = 1;
while( i < expo ){
retval *= base;
//Never did i++; or i = i + 1;
//Had to std::cout << retval; in loop to catch it
}
return retval;
}
...

Find the Narcissistic value among below numbers

#include<iostream>
#include<stack>
#include<cmath>
using namespace std;
int Narsic(stack<int> stk)
{
int x=0;
int temp=0;
int val=0;
int power_count = stk.size();
while(! stk.empty())
{
x = stk.top();
stk.pop();
temp = pow(x,power_count);
val = val + temp;
}
cout<<val;
}
int main()
{
int num,indic;
num = 1652;
stack<int> numstack;
while(num>0)
{
indic = num%10;
num = num/10;
numstack.push(indic);
}
Narsic(numstack);
return 0;
}
Basically this program is to find the Narcissistic value of a given integer, my codes can be successfully executed and it is correct, but somehow, i think , maybe it is a bit lengthy, so the purpose of posting this problem is, whether anyone can give me suggestions on how to improve the codes above?
Sorry , I'm a beginner and just started learning C++. I hope this community won't get furious against by sucky codes XD.
(Oh yeah, i do search for some codes online and implement them partially here, so if anyone saw similar codes, please be aware that i have made changes, sorry if this irritates you.)
It looks like you're largely asking about style. I'm going to take your code and edit it to be more in keeping with what I would do, then I'll comment below.
#include <iostream>
#include <stack>
#include <cmath>
using std::cout;
using std::endl;
using std::stack;
/**
* Return the Narcissistic value of the digits stored in the stack.
* A Narcissistic value is (insert description).
*/
int narsic(stack<int> stk)
{
int result = 0;
int power_count = stk.size();
while (! stk.empty() ) {
int digit = stk.top();
stk.pop();
result += pow(digit, power_count);
}
return result;
}
/**
* Entry point.
*/
int main() {
int num;
num = 1652;
stack<int> numstack;
while (num>0)
{
int indic = num % 10;
num /= 10;
numstack.push(indic);
}
int result = narsic(numstack);
cout << "Result: " << result << endl;
return 0;
}
I use Java's naming conventions. Class names begin with an upper case letter. Variables and methods begin with lower case letters. This isn't necessarily the C++ way of doing it, but I programmed Java a long time, and it's what I prefer. You'll want to find a style for your academic work, and then use whatever your future employer uses.
I prefer more whitespace to make code readable -- especially for myself. I'm nearly 60 years old, with old eyes, and as code runs all together, it gets harder and harder to read. I've added whitespace here and there.
A blanket using namespace std is considered dangerous, but I don't like sticking std:: all over the place, so I tend to add specific using statements, although not too many.
You were missing a return statement in narsic().
And you had an unusual indentation style. Old-school C/C++ is either 4 spaces or use a tab, but set your editor to 4-space tabs. You indented the braces and then indented again. That would be odd. Some people put the open brace on the same line (I moved them) and some on the next line the way you did. I actually will put them on the next line if it makes the code more readable -- like if there's an obnoxiously long and complicated if-clause.
I moved variable declaration to just as the variables were about to used. This is better for a variety of reasons, including one less initialization plus makes your code smaller. Plus, it keeps scoping rules much tighter.
I switched a num = num / 10 to num /= 10. Similar thing with result +=.
I don't like the variable name val. I changed to result. I think I might have made one or two other variables more descriptive, too.
I added function comments and I did it in the doxygen style. Commenting each method means tools can auto-generate documentation. It also helps break code up a little bit better visually. For comments, it's important to provide information not in the code. The comment for main is trivial, but having it still helps if you actually use a documentation generator -and- provides a visual break.
A change I did NOT make but would normally do: I prefer main to be the first method in my files (at the top), so I would have made a forward reference to narsic() and moved it below main. I didn't do that just because I wanted to keep the code in the same order you had it.
I moved the cout statement and included an endl.

Compilation error: More than one instance of overloaded function matches the arument list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have an assignment for school:
i. Create a classical Guitar object with price $150 and type = “classical”. Set the new price to $100 and display all the information about the Guitar object.
ii. Create an electric Guitar object with price $135 and type = “electric”. Change the price as there is a promotion and display all the information about the Guitar object.
I am trying to solve it on my own, but I am new in C++ and I'm stuck with compiler errors that I can't understand.
Here the class that I have created in my Guitar.h file.
#pragma once
#include<iostream>
#include <string>
#include<sstream>
using namespace std;
class Guitar
{
private:
string type;
double price;
public:
Guitar(string type, double price);
string getType();
double getPrice();
void setPrice(double newPrice);
void setPrice(bool promotion);
string toString();
};
This is the class implementation in my Guitar.cpp file
#include "Guitar.h"
Guitar::Guitar(string typeclass, double priceclass)
{
type = typeclass;
price = priceclass;
}
string Guitar::getType()
{
return type;
}
double Guitar::getPrice()
{
return price;
}
void Guitar::setPrice(double newPriceclass)
{
price = newPriceclass;
}
void Guitar::setPrice(bool promotion)
{
if (promotion == true)
price *= 0.9;
}
string Guitar::toString()
{
stringstream info;
info << "Guitar Type: " << type << endl
<< "Price: " << price << endl;
return info.str();
}
Finally I have my main file GuitarApp.cpp
#include"Guitar.h"
int main()
{
Guitar guitar1("Classical", 150.0);
guitar1.setPrice(100) << endl;
cout << guitar1.toString() << endl;
Guitar guitar2("Electrical", 135.0);
guitar2.setPrice(true);
cout << guitar2.toString() << endl;
}
I have 2 errors:
more than one instance of overloaded function Guitar::setPrice matches the argument list
Guitar::setPrice ambiguous call to overloaded function.
Can someone explain to me the errors and what I should do to get the code compiled?
Edit: After having changed 100 to 100.0, I got 4 more errors:
mismatch in formal parameter list
expression must have integral or unscoped enum type
cannot determine which instance of function template std::endl; is intended
'<<': unable to resolve function overload
All errors are on line 7 of my GuitarApp.cpp which is
guitar1.setprice(100.0)<<endl;
If i were to edit the price of the guitar from 100.0 back to 100, I would get the two error that I initially had.
The type of the literal 100 is int. Since int is just as easily convertible to bool as it is to double, it's ambiguous which of those functions should be called.
Changing 100 to 100.0 (a double literal) should fix this.
Normally we did not fix home works here. It is better to ask "Why this line of code did not work" instead of throwing a bunch of homeworks here in the hope to get it made ready from others...
Please also get in mind that your question is "Off topic" because:
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.
OK, your code have following syntax bugs:
guitar1.setPrice(100.) ; // see the "." behind the number!
You have to methods:
void setPrice(double newPrice);
void setPrice(bool promotion);
And you wrote:
guitar1.setPrice(100)
100 is an int and not a double and not a bool. So the compiler can not decide to make from your 100 a bool which has value true or make it a double with value 100.. So simply add a dot to make your value a floating point one which your compiler takes as double.
Next bug:
cout << guitar2.toString() << endl; // see the "2" behind guitar !
Only a typo...
Some remarks:
Splitting such a class in a header and a source file is bad! The optimizer has no chance to inline the functions.
Using using namespace std; can be bad! It is much better to write std::string and all you need to see from which namespace your definition comes. That makes a bit more work but is much better to read later, especially if you use multiple namespaces from multiple libraries.
Explanation:
It is easy to save typing some characters at a first view. But if you later (re-)use your code in an bigger application where you have to deal with a lot of libraries which may define functions/classes/what ever with the same name as one of the other library do, you start changing your code.
A simple example is to have posix read and istream read in place. Here it is also a good idea to give a '::read' to select the posix one which is not bound to a namespace.
Is it dogmatic to give the hint to not use using namespace? My personal experience is simply that if you use it, you may run into problems if your code is (re-)used later in bigger applications. And for me it is mandatory to write my code as such, which can be (re-)used without problems and or a lot of adoptions/corrections in future.
You have to decide: Save some characters to type today and may run into trouble later or do the job right now.
Maybe for the homeworks code is ok to do so. But I believe it is a good point to talk about the problems which may arise on that kind of code writing.

Difference in if()?

I'm learning C++ and I encountered 2 different types of writing a piece of code, and I wanted to know what the difference is.
Is there any difference between:
if(z==true)
{
cout << "Yes";
}
else
{
cout << "NO";
}
and:
if(z==true)
cout << "YES";
else
cout << "NO";
Technically no, but one is IMO better practice. If you omit the brace only the next line is executed, as opposed to executing everything within the brace. You can see how a quick change of code could raise problems.
Say you have
if(z==true)
cout << "YES";
else
x = 47;
and you modify it to
else
x = 47;
y = 99;
y = 99; is executed unconditionally. It's best to avoid these gotchas and just use the braces.
No, there is no difference between those two. The {} are only needed if there are multiple statements, but some people argue that always having them reduces the risk for strange bugs if more statements are added later.
This code behaves in the same way. So this is only a stylistic issue.
Many programmers prefer the first since it's more robust. It's easy to change the second one in a way that doesn't work as expected. The {} are necessary if there are multiple statements(or no statement). So changes to the second one can easily result in code where one thinks that a part is conditional/unconditional where it's not. Especially when being sloppy with indentation.
Personally I think if you have a good IDE that can auto format code the risk is small.
There is no difference at all, the first example has a block of code instead of a single statement, its just a block with a single statement in it. The former is generally considered safer to write.

cout or printf which of the two has a faster execution speed C++?

I have been coding in C++ for a long time. I always wondered which has a faster execution speed printf or cout?
Situation: I am designing an application in C++ and I have certain constraints such as time limit for execution. My application has loads printing commands on the console. So which one would be preferable printf or cout?
Each has its own overheads. Depending on what you print, either may be faster.
Here are two points that come to mind -
printf() has to parse the "format" string and act upon it, which adds a cost.
cout has a more complex inheritance hierarchy and passes around objects.
In practice, the difference shouldn't matter for all but the weirdest cases. If you think it really matters - measure!
EDIT -
Oh, heck, I don't believe I'm doing this, but for the record, on my very specific test case, with my very specific machine and its very specific load, compiling in Release using MSVC -
Printing 150,000 "Hello, World!"s (without using endl) takes about -
90ms for printf(), 79ms for cout.
Printing 150,000 random doubles takes about -
3450ms for printf(), 3420ms for cout.
(averaged over 10 runs).
The differences are so slim this probably means nothing...
Do you really need to care which has a faster execution speed? They are both used simply for printing text to the console/stdout, which typically isn't a task that demands ultra-high effiency. For that matter, I wouldn't imagine there to be a large difference in speed anyway (though one might expect printf to be marginally quicker because it lacks the minor complications of object-orientedness). Yet given that we're dealing with I/O operations here, even a minor difference would probably be swamped by the I/O overhead. Certainly, if you compared the equivalent methods for writing to files, that would be the case.
printf is simply the standard way to output text to stdout in C.
'cout' piping is simply the standard way to output text to stdout in C++.
Saying all this, there is a thread on the comp.lang.cc group discussing the same issue. Consensus does however seem to be that you should choose one over the other for reasons other than performance.
The reason C++ cout is slow is the default sync with stdio.
Try executing the following to deactivate this issue.
ios_base::sync_with_stdio(false)
http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/
http://msdn.microsoft.com/es-es/library/7yxhba01.aspx
On Windows at least, writing to the console is a huge bottleneck, so a "noisy" console mode program will be far slower than a silent one. So on that platform, slight differences in the library functions used to address the console will probably make no significant difference in practice.
On other platforms it may be different. Also it depends just how much console output you are doing, relative to other useful work.
Finally, it depends on your platform's implementation of the C and C++ I/O libraries.
So there is no general answer to this question.
Performance is a non-issue for comparison; can't think of anything where it actually counts (developing a console-program). However, there's a few points you should take into account:
Iostreams use operator chaining instead of va_args. This means that your program can't crash because you passed the wrong number of arguments. This can happen with printf.
Iostreams use operator overloading instead of va_args -- this means your program can't crash because you passed an int and it was expecting a string. This can happen with printf.
Iostreams don't have native support for format strings (which is the major root cause of #1 and #2). This is generally a good thing, but sometimes they're useful. The Boost format library brings this functionality to Iostreams for those who need it with defined behavior (throws an exception) rather than undefined behavior (as is the case with printf). This currently falls outside the standard.
Iostreams, unlike their printf equivilants, can handle variable length buffers directly themselves instead of you being forced to deal with hardcoded cruft.
Go for cout.
I recently was working on a C++ console application on windows that copied files using CopyFileEx and was echoing the 'to' and 'from' paths to the console for each copy and then displaying the average throughput at the end of the operation.
When I ran the console application using printf to echo out the strings I was getting 4mb/sec, when replacing the printf with std::cout the throughput dropped to 800kb/sec.
I was wondering why the std::cout call was so much more expensive and even went so far as to echo out the same string on each copy to get a better comparison on the calls. I did multiple runs to even out the comparison, but the 4x difference persisted.
Then I found this answer on stackoverflow..
Switching on buffering for stdout did the trick, now my throughput numbers for printf and std::cout are pretty much the same.
I have not dug any deeper into how printf and cout differ in console output buffering, but setting the output buffer before I begin writing to the console solved my problem.
Another Stack Overflow question addressed the relative speed of C-style formatted I/O vs. C++ iostreams:
Why is snprintf faster than ostringstream or is it?
http://www.fastformat.org/performance.html
Note, however, that the benchmarks discussed were for formatting to memory buffers. I'd guess that if you're actually performing the I/O to a console or file that the relative speed differences would be much smaller due to the I/O taking more of the overall time.
If you're using C++, you should use cout instead as printf belongs to the C family of functions. There are many improvements made for cout that you may benefit from. As for speed, it isn't an issue as console I/O is going to be slow anyway.
In practical terms I have always found printf to be faster than cout. But then again, cout does a lot more for you in terms of type safety. Also remember printf is a simple function whereas cout is an object based on a complex streams hierarchy, so it's not really fair to compare execution times.
To settle this:
#include <iostream>
#include <cstdio>
#include <ctime>
using namespace std;
int main( int argc, char * argcv[] ) {
const char * const s1 = "some text";
const char * const s2 = "some more text";
int x = 1, y = 2, z = 3;
const int BIG = 2000;
time_t now = time(0);
for ( int i = 0; i < BIG; i++ ) {
if ( argc == 1 ) {
cout << i << s1 << s2 << x << y << z << "\n";
}
else {
printf( "%d%s%s%d%d%d\n", i, s1, s2, x, y, z );
}
}
cout << (argc == 1 ? "cout " : "printf " ) << time(0) - now << endl;
}
produces identical timings for cout and printf.
Why don't you do an experiment? On average for me, printing the string helloperson;\n using printf takes, on average, 2 clock ticks, while cout using endl takes a huge amount of time - 1248996720685 clock ticks. Using cout with "\n" as the newline takes only 41981 clock ticks. The short URL for my code is below:
cpp.sh/94qoj
link may have expired.
To answer your question, printf is faster.
#include <iostream>
#include <string>
#include <ctime>
#include <stdio.h>
using namespace std;
int main()
{
clock_t one;
clock_t two;
clock_t averagePrintf;
clock_t averageCout;
clock_t averagedumbHybrid;
for (int j = 0; j < 100; j++) {
one = clock();
for (int d = 0; d < 20; d++) {
printf("helloperson;");
printf("\n");
}
two = clock();
averagePrintf += two-one;
one = clock();
for (int d = 0; d < 20; d++) {
cout << "helloperson;";
cout << endl;
}
two = clock();
averageCout += two-one;
one = clock();
for (int d = 0; d < 20; d++) {
cout << "helloperson;";
cout << "\n";
}
two = clock();
averagedumbHybrid += two-one;
}
averagePrintf /= 100;
averageCout /= 100;
averagedumbHybrid /= 100;
cout << "printf took " << averagePrintf << endl;
cout << "cout took " << averageCout << endl;
cout << "hybrid took " << averagedumbHybrid << endl;
}
Yes, I did use the word dumb. I first made it for myself, thinking that the results were crazy, so I searched it up, which ended up with me posting my code.
Hope it helps,
Ndrewffght
If you ever need to find out for performance reasons, something else is fundamentally wrong with your application - consider using some other logging facility or UI ;)
Under the hood, they will both use the same code, so speed differences will not matter.
If you are running on Windows only, the non-standard cprintf() might be faster as it bypasses a lot of the streams stuff.
However it is an odd requirement. Nobody can read that fast. Why not write output to a file, then the user can browse the file at their leisure?
Anecdotical evidence:
I've once designed a logging class to use ostream operators - the implementation was insanely slow (for huge amounts of data).
I didn't analyze that to much, so it might as well have been caused by not using ostreams correctly, or simply due to the amount of data logged to disk. (The class has been scrapped because of the performance problems and in practice printf / fmtmsg style was preferred.)
I agree with the other replies that in most cases, it doesn't matter. If output really is a problem, you should consider ways to avoid / delay it, as the actual display updates typically cost more than a correctly implemented string build. Thousands of lines scrolling by within milliseconds isn't very informative anyway.
You should never need to ask this question, as the user will only be able to read slower than both of them.
If you need fast execution, don't use either.
As others have mentioned, use some kind of logging if you need a record of the operations.