Which one is preferred when checking arguments? [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
For example, I have a method which accepts some arguments like
method1(int i)
the argument int should be either 1 or 2
I can use assert (i == 1 || i ==2)
or throw exception if (!(i==1) || (i==2)) throw std::exception
which one is better. I am always confused about assert vs explicit throw.

It really depends on the situation.
There are four major groups of error handling:
assert - used to deal with programming errors ("We don't expect this function to get a NULL pointer, and if it does, it's because some other part of our code is broken, and it should NEVER happen"). If the assert wasn't there, the code would probably crash, loop forever, or otherwise "fail".
exceptions - such as std::invalid_argument - this is more used when the program EXPECTS things to go wrong, and there is some way to "try again". More likely when the actual user is using the program wrong - e.g. inputs from keyboard/file, etc. As the name states, this should be an "exception" - something unusual and unexpected.
return value - when an error is entirely likely (trying to see if the serial port is on port COM1, COM2, COM3 or COM4 or "is the result of the equation matching what I expect yet?")
Let it crash - if the inputs are wrong, the application runs out of memory, etc, just crash. It may seem like a rough method, but sometimes there's not much better you can do anyway - what are you going to ACTUALLY do in the middle of your compiler if some linked list is broken and the next node is not pointing at your special sentry pointer, but to NULL? Printing a message may be a little better, but not a huge amount.

Is the integer passed to method1 always going to be done so by a programmer, or might it be passed in by the users of your application?
Assert,
for example if your code looks like this:
int i;
if ( condition ) {
i = 1;
}
else {
i = 3;
}
method1(i);
If this is the case, you'd likely want to use an assert, because it indicates you (the programmer) has made an error. If i = 3, you want your program to blow up and make it obvious there is a problem in your code, so you can catch it before you release it to your clients.
Throw an exception,
on the other hand, if your code looks like this:
int i;
cin >> i;
method1(i);
You're passing the user's input to the function. You can't anticipate what they might enter. So if it's an invalid value, you should throw an exception or return an error code and handle it accordingly (e.g., print out a message to the user saying they have entered an invalid number).

Generally asserts are checked in debug builds but not release builds. If you want to save time and skip the check in your final released code, then asserts are the way to go. If your function needs to blow up in the face of unexpected input even in release, then the exception may be the way to go.
Of course the details of exactly what you should do for error conditions will vary with context beyond what was provided in your example.

Related

Difference between return 0 and -1 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Can anyone please explain the difference between return 0 and -1 used in c++? I have read many articles and posts from other programmers saying that return 0 means the program is successful and -1 means the program has an error. But what I don't get is why use these statements when the compiler will generate an error if there is one in the program anyway? Please explain in detail what these statements really mean.
This has absolutely nothing to do with the compiler.
The compiler will report syntax errors.
The return codes are used to report if the program completed successfully.
("Success" depends on what the program was intended to do).
For example:
// Program SearchTerm "term to find"
int main(int argc, char* argv[])
{
bool search_successful = false;
[ ... do work ... ]
if (search_successful)
{
return 0; // The search worked.
}
else
{
return -1; // The search failed
}
}
Example usage:
SearchTerm "Microsoft"
More than 1 million results found... returned Success
SearchTerm "asldfjpu"
No results found... returned Failure
When a program reports success or failure, it can be integrated in the Scripts such as:
#!/bin/bash
if `SearchTerm "Microsoft"`; then
GetTopResults "Microsoft"
else
echo "No results found, no Top Results to retrieve"
fi
The return value of int main() is the so called exit code of the program. This is already so in C (which has no exceptions) and is there to basically tell to caller how it went. A exit code of zero means success and every other exit code (but normally one uses only positive ones) means that something went wrong. Sometimes programms will document what a certain exit code means i.e. if a file was not found or an allocation failed etc.
This is a very important part of scripting for example bash scripts, which know in this way if a called command went right or wrong. Even if your program crashes with an exception, the programm will generate an exit code (which will be non-zero). In bash you can see the exit code of the last run program with echo $?, so you can check that out for yourself.
A return is simply the value returned by any function. At the end of a function, the computer is able to accept a single value to take back with it when it returns to the rest of the program. In the case of the function int main(), with which you are probably familiar, the return value is used as an indication of the success of the program.
main() is simply the entry point of the program you are running. It's the first function called by your computer when the program starts (with some exceptions)
Theoretically, you could return any integer from main().
The only "accepted" thing is that anything that is non-zero is generally some error or fault. So a return 0; indicates success, while return -1; might indicate some kind of error. The truth is, the value returned from main() doesn't really matter, and won't affect how your program runs.
If you're asking about the value returned by main, there are two defined values that you can return: EXIT_SUCCESS and EXIT_FAILURE. Those values are defined in the header <stdlib.h> and in the header <cstdlib>. You can also return the value 0, which is equivalent to returning EXIT_SUCCESS. There are no other meaningful values in C or C++, although your implementation can provide meanings for other values.
I am assuming that you are returning 0 or -1 from the main program as your program exits. What this does is inform the calling program the success or failure of the program. This is not very handy if you just run the program at a command prompt but if your program is called within a script (Perl,PHP, python, PowerShell, etc) you can test to see if the program was successful.
In a nutshell, if your program is called by another program, the calling program can test for success or failure and respond appropriately.
the program is successful and -1 means the program has an error.
Please explain in detail what these statements really mean.
There are situations where a function cannot proceed further, and cannot complete the task that it is specified for it. Such situation is typically called an error. There are many possible sources of errors. One example of that is a function that has pre-conditions for the inputs that were not satisfied by the caller of the function. An example of such pre-condition is square root function that calculates rational numbers (i.e. not complex): There is no result for negative input.
When an error is encountered, it must somehow be communicated to the caller. There are many techniques, but we shall not cover all of them in detail here. I'll mention that one option in C++ is exceptions. Exceptions technique has some useful properties, but it is not universally applicable to all situations.
Another, very simple technique is to return an error code which is an integer value. If we choose 0 to signify no error, the caller of the function can check for error with following pattern:
int error = function(arguments)
if (error) {
// handle error here
}
This pattern is very common in C APIs. C++ inherits C standard library, and it is common to take advantage of C libraries so it is common to encounter this in C++ as well.
Sometimes, a function needs to use the return value for some other purpose. For example, the open call from POSIX standard returns an integer called "file descriptor", which is a positive integer. Since some of the values in the domain of the return type are not used (negative numbers), it can be used to represent error condition as well. Although any negative number is available, -1 was chosen, and this is also quite conventional. In some other APIs different negative numbers represent different errors. Another approach is to store error information elsewhere. The chosen approach in POSIX is to store the error code in a separate variable.
In conclusion: Integer return values are a technique of communicating errors, and 0 is conventionally used to represent success and -1 is often used to represent erroneous execution. The meaning of the return value of a function should be documented by the implementer, and the documentation should be studied carefully by the user of the function.
But what I don't get is why use these statements when the compiler will generate an error if there is one in the program anyway?
It's unclear what you expect here. The compiler cannot read the programmer's mind and know all cases where the program should have an error. It can only tell whether the program is well-formed or not (and maybe give some helpful warnings about obvious mistakes if you're lucky).
It is the programmer's responsibility to consider the error conditions of the program.
The only difference between 0 and -1, as far as the compiler is concerned, is that they are two different numbers. Nothing is assumed whatsoever about their "success" or "failure" status (except in main in which the return value is ignored anyway).
The rest are (mostly bad) conventions used by developers. Usually < 0 for failure and 0 for success and you have created a nice bug when you test against bool (in which -1 is true and 0 is false).
One should use enums or, at least, something more recognizable as in windows HRESULT.
It basically means that anything other then 0 means something bad happened during execution of your program. The program could not deal with it so it exited with the status code.
Often when working with shell you will notice that some of commands exit with non 0 status code. You can check that value by running echo $? command.
And finally you can use return codes to communicate to the client what happend. That is if you describe what return codes can your program return.

Performance when using sequence of operations in a single line in cpp [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Recently I have started looking into C++ from the basics and got to know (to my surprise) that I can give series of expressions in a single line separated by commas in some cases as below
//it'll execute all the expressions mentioned after condition seperated by comma
for(int i=0;condition;++i,++x,cout<<"in for loop"<<endl,z = z*2);
(x>y)? ++z,z1 = z*2, cout<<"printing statement"<<endl:cout<<"condition failed"<<endl,z = z/2;
Here, I have a confusion after this is working. Is it safe to code in that way or is there any problem coding in such a way?
Please clarify!!!
Correct me if i'm wrong anywhere, I'm just curious to know why most of the programmers don't use this way (I haven't seen such kind of lines anywhere)
The comma operator , evaluates each of its operands in sequence. In standardese, there is a sequence point between the evaluation of the left operand and the right operand.
In a expression which contains a comma operator, the value of the left operand is discarded and the expression takes on the value of the right operand. In both of the examples above, the comma operator is used in a void context, so none of the values are used.
So a statement like this where the value of the comma operator is not used:
exp1, exp2, exp3, exp4;
Is equivalent to the following sequence of statements:
exp1; exp2; exp3; exp4;
The first example is equivalent to the following:
for(int i=0;condition;) {
++i;
++x;
cout<<"in for loop"<<endl;
z = z*2;
}
And the second example:
if (x>y) {
++z;
z1 = z*2;
cout<<"printing statement"<<endl;
} else {
cout<<"condition failed"<<endl;
z = z/2;
}
Note that this is considerably more readable that the one-line versions. It's also easier to debug. Since debuggers typically step through code a line at a time, it breaks up the flow and is more granular.
Not indenting and spacing your code is not less costly regarding performance. It is unreadable, confusing and a pain to understand for you and for anyone who'd have to work with it.
Lot of people will prefer a well-syntaxed, beautifully and efficiently-indented code than a top-performance one. You can modify, debug and refract a code which might not work but has the advantage to be understandable.
On the other hand, very few codes remain unchanged and stay unread. There will always be a time when someone, may be you, will have to read it again and if it looks like the one if your OP, it will be very time costly to do.
It is allowed. In my opinion and i say without a reference that in general other programmers do not find your 'for' loop very readable. Sometimes in a for loop you want to do other things then just for (int i = 0; i < 10; ++i){"do something"}For example increment 'i' in every loop with two. Reading code should be like reading a text. If you are reading a book you do not want it to be unnecessary difficult.
Your other question was about the safety of the statement. The biggest problem with the code is that you might get confused about what you are doing exactly. Bugs are caused by human errors (computers are deterministic and are executing machine code which ultimately has been written by a human) and the question about safety mainly depends on how you define it.
To give you some tips. When i just started programming C++ i looked a lot on CPP reference. I will give you a link where you can read about the syntax and what is allowed/possible. On this website there are quite a lot of examples on all kinds of statements. They will in general not put 5 or 6 operations within in a single line. If there are more variables that you want to change then you might want to do that in the scope of the for loop so it will be more readable instead of inside the for loop.
http://en.cppreference.com/w/cpp/language/for

Error in Strings assignment. (C++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I've looked everywhere and I've found one for php but not c++. I'm making a little console rpg for a project in my into to c++ class and I'd like to avoid functions and/or if possible--but if not I'll use them.
Sample code:
int main(){
string pName;
string pWpnName;
int pDamage=0;
int wdSwrdD=1;
if (pDamage==wdSwrdD)pWpnName="Wooden Sword";
cout<<"Please enter a name";
cin>>pName;
pDamage++:
cout<<"Name: "<<pName<<endl;
cout<<"Weapon: "<<pWpnName<<endl;
return 0}
But whenever I do this it outputs: Name: pName (like it's supposed to) and Weapon:. It just stays blank and I have a feeling it's something to do with how I'm using strings...
You do not understand basics of how imperative languages (and C++ is one of them) work. Program executed statement by statement, and your if condition checks pDamage==wdSwrdD only once - when execution flow goes through that statement. So the fact that you increase pDamage later will not magically change pWpnName (and you need to change comparison operator == to assignment operator = in that if condition in addition to that, but I assume this is a typo).
So you most probably need a loop where execution flow is repeatedly goes through your if statement (that's what loops are created for), but it is difficult to say anything more based on information you provided.
You can use the getline() function:
cout<<"Please enter a name"<<endl;
getline(cin, pName);
pDamage++;
The function can get a line from a stream, set std::cin as the steam argument, and assign a line input to a variable.
Your problem is that you've made a typo: == is equality comparison, while = is assignment. So, your section of code should be changed:
if (pDamage==wdSwrdD)
pWpnName=="Wooden Sword"; // here you're doing comparison
...to:
if (pDamage==wdSwrdD)
pWpnName="Wooden Sword"; // here you're doing assignment
Most compilers should generate a warning for this behavior because it's an easy typo to make, but can be difficult to catch.
In your program you have not initialized the strings and your are taking user input for pName and therefore it displays the name . In case pWpnName it's not initialized while declaring and the "if condition never becomes true" because you have initialized pDamage=0 and wdSwrD=1 and as we know if(0==1) is never true the string pWpnName never gets initialized to Wooden Sword so it displays blank.

How do I write a code that says: "if I can do this, do this. Otherwise do nothing", in Python 2.7?

How do I write a code that says: "if I can do this, do this. Otherwise do nothing", in Python 2.7?
I added the code that is not working below.
words = ["glad", "lycklig", "fin", "vacker", "sot", "blomming"]
word_index = words.index("sot")
focus_word = words[word_index]
tre = words[word_index+1]
if words[word_index+2] == True:
fyra = words[word_index+2]
else:
print "the list is not long enough"
So I want to get the word that is two words after "sot" if there is one. In this case there isn't, and then I just want to skip that command.
There are two general "philosophies" to avoiding errors in Python code.
One, known as "look before you leap" (LBYL) says that you should check that the values you're operating on are correct before you do anything that relies on that correctness. This is a good approach where the errors are not obvious ones, like exceptions, but rather where you get invalid answers when given invalid input.
For your code, the best way to do this kind of check in your code is to use if word_index + 2 < len(words) to directly check if the index you're going to be looking up is too large.
The other design for avoiding errors doesn't actually avoid them completely, rather it lets the errors occur and deals with them afterwards. This is known as "easier to ask forgiveness than permission" (EAFP), and usually involves try and except blocks in Python.
For your code, you could use this code to catch the IndexError that will be raised if word_index+2 is off the end of the words list:
try:
fyra = words[word_index+2]
except IndexError:
print "No such value"
You might need more logic though, since fyra won't be defined if you hit the except case. You might want to quit with sys.exit() or set fyra to some default value at the end of the except instead of just printing the error message.
Note that it's important to think carefully about what exceptions you're catching in an except clause. You don't want to catch all errors (with a bare except:) in most cases, since that can hide unexpected errors that really should crash the program and show you the stack trace (so you can fix the bug causing them to occur). It's often best to catch the most specific exception type you can, and wrap your try around the smallest block of code you can.

What type of input check can be performed against binary data in C++?

let's say I have a function like this in C++, which I wish to publish to third parties. I want to make it so that the user will know what happened, should he/she feeds invalid data in and the library crashes.
Let's say that, if it helps, I can change the interface as well.
int doStuff(unsigned char *in_someData, int in_data_length);
Apart from application specific input validation (e.g. see if the binary begins with a known identifier etc.), what can be done? E.g. can I let the user know, if he/she passes in in_someData that has only 1 byte of data but passes in 512 as in_data_length?
Note: I already asked a similar question here, but let me ask from another angle..
It cannot be checked whether the parameter in_data_length passed to the function has the correct value. If this were possible, the parameter would be redundant and thus needless.
But a vector from the standard template library solves this:
int doStuff(const std::vector<unsigned char>& in_someData);
So, there is no possibility of a "NULL buffer" or an invalid data length parameter.
If you would know how many bytes passed by in_someData why would you need in_data_length at all?
Actually, you can only check in_someData for NULL and in_data_length for positive value. Then return some error code if needed. If a user passed some garbage to your function, this problem is obviously not yours.
In C++, the magic word you're looking for is "exception". That gives you a method to tell the caller something went wrong. You'll end up with code something like
int
doStuff(unsigned char * inSomeData, int inDataLength) throws Exception {
// do a test
if(inDataLength == 0)
throw new Exception("Length can't be 0");
// only gets here if it passed the test
// do other good stuff
return theResult;
}
Now, there's another problem with your specific example, because there's no universal way in C or C++ to tell how long an array of primitives really is. It's all just bits, with inSomeData being the address of the first bits. Strings are a special case, because there's a general convention that a zero byte ends a string, but you can't depend on that for binary data -- a zero byte is just a zero byte.
Update
This has currently picked up some downvotes, apparently by people misled by the comment that exception specifications had been deprecated. As I noted in a comment below, this isn't actually true -- while the specification will be deprecated in C++11, it's still part of the language now, so unless questioner is a time traveler writing in 2014, the throws clause is still the correct way to write it in C++.
Also note that the original questioner says "I want to make it so that the user will know what happened, should he/she feeds [sic] invalid data in and the library crashes." Thus the question is not just what can I do to validate the input data (answer: not much unless you know more about the inputs than was stated), but then how do I tell the caller they screwed up? And the answer to that is "use the exception mechanism" which has certainly not been deprecated.