Is there any difference between the following 2 codes
for (int i = 0; i < 3; i++)
cout << i << endl,
countSteps ++;
and
for (int i = 0; i < 3; i++){
cout << i << endl;
countSteps ++;
}
The comma character has different meaning under different syntactic elements.
In your case, it is a comma operator.
For the sake clarity, the following does not constitute a statement.
cout << i << endl,
The following does.
cout << i << endl,
countSteps ++;
As does the following
cout << i << endl;
A semi-colon ends a statement. A comma does not.
For your posted code, the two blocks of code won't make any difference to the outcome of your program. However, it is good to know the difference between the syntactic constructs.
In general, they can have different behavior based on the value the expressions of the comma operator evaluate to. See https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator for additional details.
No, there is no difference in this case. (Except for the second snippet not looking ugly.)
In general case, operator, could be overloaded. Then the first option might can cause weird effects.
Related
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 2 months ago.
Improve this question
I did not write this code.
i'm on my 3rd day of coding in C++ and i'm having a hard time understanding how incremnent works in general.
int main()
{
int antal_ord {};
double medellangd {};
string kort_ord;
string langt_ord;
int min_length {100};
int max_length {};
string S;
cout << "Mata in en text:\n" << endl;
while (cin >> S)
{
if (S.length() > max_length)
{
max_length = S.length();
langt_ord = S;
}
if (S.length() < min_length)
{
min_length = S.length();
kort_ord = S;
}
medellangd+=S.length();
antal_ord++;
}
if (antal_ord == 0)
{
cout << "Inga ord matades in." << endl;
}
else {
medellangd = (medellangd / antal_ord);
round(medellangd);
cout << "Texten innehöll " << antal_ord << " ord." << endl;
cout << "Det kortaste ordet var " << '"' << kort_ord << '"' << " med "
<< kort_ord.length() << " tecken." << endl;
cout << "Det längsta ordet var " << '"' << langt_ord << '"' << " med "
<< langt_ord.length() << " tecken." << endl;
cout << "Medelordlängden var "<< fixed << setprecision(1) << medellangd << " tecken.";
}
return 0;
}
antal_ord is the variable for the amount of words written in this scenario.
In the line where it says "cout << "Texten innehöll " << antal_ord << " ord." << endl;" how does it know how many words have been written? The only time this variable is used before this line is when the variable gets incremented, but how does that let the variable know how many words have been written in total?
and also the .length command, does it basically just count the amount of letters written?
There's really nothing special going on here. Every time you read one word with cin >> S, you increment antal_ord by one. Since you started with zero words written and antal_ord==0, at the end antal_ord will equal the number of words read from cin.
Similarly, S.length() returns the number of letters currently in S. In your case, that is exactly the number of letters read from cin since you didn't chance S after reading. But if you did S += " some extra letters, then S.length() will of course change.
When you'll learn about most programming languages, you'll start off with basics: syntax, data types, declarations (vars + funcs as well as other possible concepts), loops, calls, math operations and other code-control techniques relevant to each programming language.
What you'll see about most (and I;ll try to "rewind" from the generalization I started with and back down to C/C++) is that you have the following type of math operation variations when it comes to addition (let's focus on this, as it's more on point with the question).
result in a separate variable, in our case b: b = a + 1;
result in the same variable: a += 1;
incrementing the value of the variable: a++;
Expanding on it:
In the first case, b will have its value overwritten and is dependent on a different values (in this case the value of a and 1). What you need to focus on here is that a is NOT changed.
In this case, a receives a new value and is incremented by the right-side-value, in our case 1. a is changed by adding one (not incrementing)
In our case, similar to #2, the value of 8a* is updated, but the incrementation is done by 1.
Apart from syntactic sugar or code style preference, the difference between each is also in the way the variables are assigned their values (more formally said, in the assembly code "underneath"). This topic is a lot more complicated for someone that started programming, but focusing on the question, the answer is simply that ++ increments the value by 1.
Also note that there is a difference in certain coding flows between ++a and a++. Mainly in loops. For ++a the value is set before executing the code, using the already incremented value in the code, while a++ uses the current value of a first, then increments it.
Try it like this:
int i = 0;
while (++i < 100)
{
std::cout << i << std::endl;
}
... versus...
int i = 0;
while (i++ < 100)
{
std::cout << i << std::endl;
}
Then count how many lines each case wrote.
There is also a small caveat you should be aware of, it's a bit more advanced, so it's just a little "FYI" for you. There are two C++ techniques called "function overloading" and "operator (re)definition". Let's focus on the second one. You could build your own data type (for example a struct or class) and implement your own operators that do something other than what their arithmetic counterparts do. You'll see this in iterator definitions. In that case ++ is not "actual value incrementation" (so it's not a math calculation), but rather switching to the next item in a list. Once you reach std::vector lessons you'll encounter that.
Consider:
for(int i = 10; b >= i; i++){
if(i%2 == 0)
cout << "even" << endl;
else
cout << "odd" << endl;
}
for(int i = 10; b >= i; i++){
if(i%2 == 0){
cout << "even" << endl;
}else{
cout << "odd" << endl;
}
}
Both of these code work with the only difference being the curly brackets for the if else statement. When should I use curly brackets and when not?
They're called braces or curly brackets, not to be confused with the "curly arrow" in some languages, ~>.
In C, and by inheritance C++, these are optional on single-line if statements, but as many, many bugs have been created by omitting them you'd be advised to use them as a matter of principle even when they're redundant.
That is a mistake like this is easy to overlook:
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
Where it seems like that goto is conditional, yet it's not, it just drops through. This is the huge OpenSSL bug that caught everyone by surprise, and if veteran developers can mess it up, so can you.
The second form is the most reliable, least ambiguous, especially when formatted according to typical conventions:
for (int i = 10 ; b >= i;i++) {
if (i%2 == 0) {
cout << "even" << endl;
}
else {
cout << "odd" << endl;
}
}
for is a statement, not a function, so the syntax is for (...) with a space. Functions have no space, like f(...). Omitting the space implies for is a function, which it absolutely is not. The same goes for if, while and so on.
It's worth noting that the original code can actually be reduced to:
for (int i = 10 ; b >= i;i++)
if (i%2 == 0)
cout << "even" << endl;
else
cout << "odd" << endl;
Since that if is a single statement, even with the else clause attached.
Again, this is not advised because the rules of what is and isn't a single statement can be confusing.
Google has a detailed C++ style guide that may help you. In particular, it says that
In general, curly braces are not required for single-line statements, but they are allowed if you like them; conditional or loop statements with complex conditions or statements may be more readable with curly braces. Some projects require that an if must always have an accompanying brace.
If the 'if', 'else' or 'for' structures have only one statement inside them, you can decide not to use the curly brackets. However, I would recommend to use them in order to improve the code readability.
#include<iostream>
using namespace std;
int main(){
char c = 'a';
int numb;
for (int i = 1; i <= 25 ; i++){
cout << c << "," << c++ << endl;
}
}
Why is it that when I print the output above, the following will get printed:
b,a
c,b
d,c
But I was expecting:
a,b
b,c
c,d
If you are not compiling to the C++17 Standard revision or more recent you have encountered undefined behaviour. The older C++ Standards do not specify the sequencing of
cout << c << "," << c++ << endl;
so there are no guarantees on when that c++ will occur. The only thing you can count on is the c++ term will be the initial value because ++ increments after the value is collected.
a,a
or
b,a
are valid outputs.
As of C++17 the Standard guarantees that all side effects will be resolved before proceeding to the next <<. << c will be resolved, not that there is much to resolve, before << "," starts. << c++ comes even later in the chain. This means you should always see
a,a
b,b
c,c
See the notes on Undefined Behaviour at the bottom of Order of evaluation
I believe that it has to do with the order of operations here. The stream operator (<<) operates from right to left. Meaning that in the first run, c++ evaluates to "a", but causes c to be iterated up to "b".
I have two snippets:
while (indent-- > 0)
{
out << " ";
}
while (indent > 0)
{
indent -= 1;
out << " ";
}
As far as I can see, there isn't any undefined behaviour going on in the first snippet (see here).
My question is: are these two snippets equivalent?
I am not so sure, because the -= operator has a higher precedence than the compare operator, and should therefore be performed first in the first snippet. The second snippet however, only performs this after comparison.
They will run the body of the loop the same number of times, but they are not the same.
The first will decrement indent one extra time, leaving indent at -1, because the -- operator will run whether the condition succeeds or fails.
The second will leave indent at 0. Here's a complete working example:
#include <iostream>
int main()
{
int indent = 3;
while (indent-- > 0)
{
std::cout << "First "; // Prints three times
}
std::cout << indent << std::endl; // Prints -1
indent = 3;
while (indent > 0)
{
indent -= 1;
std::cout << "Second "; // Prints three times
}
std::cout << indent << std::endl; // Prints 0
}
// Output:
// First First First -1
// Second Second Second 0
There's no difference between the two because indent-- is a post-increment - it will return the previous value of indent - there would be a difference for while (--indent > 0) though.
So, for basic types, they're equivalent.
Since this is C++, though, you can just as well define your own class, have indent an object of that type, overload -- and =(int) and > and have them behave completely different (I hope this isn't the case).
EDIT: correct, the value of indent isn't the same.
I think they are different. What is missing is initialization of indent and its type.
First loop will always decrement after comparison, second only when condition was true. If (indent > 0) is true before loop, they behave exactly the same way. If indent==0 however, first loop will make it -1 without printing it once. Second will not print any indent, but wont decrease indent also.
So, they are different in some cases.
#include <iostream>
using namespace std;
int main (void) {
cout << " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl << "" << endl;
for (int c = 1; c < 10; c++) {
cout << c << "| ";
for (int i = 1; i < 10; i++) {
cout << i * c << '\t';
}
cout << endl;
}
return 0;
}
Hey so this code produces a times table...I found it on Google Code's C++ class online...I'm confused about why "i" in the second for loop resets to 1 every time you go through that loop...or is it being declared again in the first parameter?
Thanks in advance!
It "reverts" to 1 because you explicitly set it to 1 as the start condition of the loop...
The "i" name does not exist outside this loop, so each time this loop is run (for each iteration of 'c'), then "i" is a new variable, set to a start of 1.
As TZHX has written. FOR statements usually have three clauses that are in the parantheses (technically they always have three but you don't have to specify them), and a statement that is repeated (often a statement block).
Of those three clauses, the first is an initializer, the second controls the looping, and the third is the increment. So as TZHX says, i is reset to 1 at the beginning due to the initializer clause. This will keep repeating while i<10 (the second clause), and i is incremented by 1 with each iteration (the third clause).