This question already has answers here:
How does the Comma Operator work
(9 answers)
Closed 9 years ago.
When I use two variables in a for loop with different conditions two conditions like I have used below i<3,j<2 the for loop is always executing till the second condition fails.
#include<iostream>
#include<conio.h>
using namespace std ;
int main()
{
int i,j ;
for(i=0,j=0;i<3,j<2;i++,j++)
{
cout<<"hello" ;
}
getch() ;
return 0 ;
}
In that code, hello is printed 2 times. Why?
If I use i<3,j<10, "Hello" is printed 10 times. I can't understand why the first condition is being neglected. Is it compiler dependent or something else?
Every thing works normal if I replace with conditions like || (OR) or &&(AND).An other thing is that I cannot initialize i and j in the for loop itself, it is showing me an error, but works fine when I declare variables in C style or one variable outside the for loop, why is it so?
Compiler I have used is Orwell Dev C++.
Thanks in advance.
for(i=0,j=0;i<3,j<2;i++,j++)
is equivalent to
for(i=0,j=0;j<2;i++,j++)
The comma expression takes on the value of the last expression.
Whichever condition is first, will be disregarded, and the second one will be used only.
The for loop consists of:
for(START_STATEMENT; CONDITION_EXPRESSION, LOOP_EXPRESSION) BODY_BLOCK
Where:
START_STATEMENT is any single statement, which may include variable declaration. If you want to declare 2 variables, you can write int i=0, j=0, but not int i=0; int j=0 because the latter are actually 2 statements. Also node, that variable declaration is a part of statement, but cannot be a part of (sub) expression. That is why int i=0, int j=0 would also be incorrect.
CONDITION_EXPRESSION is any single expression that evaluates to a boolean value. In your case you are using a coma operator which has the following semantics: A, B will do:
evaluate A (it will evaluate, not just ignore)
ditch the result of A
evaluate B
return B as the result
In your case: i<3,j<2 you are comparing i<3, you are just ignoring the result of this comparison.
Comma expressions are useful when the instructions have some side effects, beyond just returning a value. Common cases are: variable increment/decrement or assignment operator.
LOOP_EXPRESSION is any single expression that does not have to evaluate to anything. Here you are using the comma expression again, ignoring the result of the left-hand-side. In this case however, you are not using the result anyway, and just using the ++ side effect - which is to increment the values of your variables.
BODY_BLOCK is either a single statement or a block, encapsulated with curly braces.
The above for can be compared to:
{
START_STATEMENT;
while(EXPRESSION) {
BODY_BLOCK;
LOOP_EXPRESSION;
}
}
The c complier always used second condition.
therefore j<2 is used.
use this for loop
for(i=0,j=0;j<10;i++,j++)
Related
This question already has answers here:
Are compound statements (blocks) surrounded by parens expressions in ANSI C?
(2 answers)
Closed 4 years ago.
I have the following code:
int main() {
int i=0;
int j=({int k=3;++i;})+1; // this line
return 0;
}
It compiles and runs. If I remove the () from "this line", then it doesn't compile.
I'm just curious what syntax rule is being applied here.
The {} contains 2 statements, and the last statement indicates the "return" value of this code block. Then why does it need an extra () pair to make this return value usable?
That's a statement expression, and it's a GCC-specific extension.
From the linked reference:
A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression.
A compound statement is a curly-brace enclosed block of statements.
I have a following problem.
I have two vectors correct_data_labels.label and data_labels.label , label is the vector<int > whereas data_labels and correct_data_labels are the instance of my class.
I have a method where I have if statement inside it. When I use IF statement, the argument that I used inside the parenthesis does an arithmetic and changes the value. As seen in the code below: When I run the code it replaces the value written inside an IF statement. So data_labels.label[row] is replaced by correct_data_labels.label[row]
unsigned int num=0;
double percentage=0.00;
for(register unsigned int row=0;row<data_labels.label.size();row++)
{
if((data_labels.label[row]=correct_data_labels.label[row]))
{
num=num+1;
}
}
percentage = (num/data_labels.label.size());
This code is written in c++, I suppose other programming paradigms can answer the above query too.
You used the assignment operator = instead of the equality operator ==. You probably got a warning about it which is why you have an extra set of parenthesis around the expression: suggest parentheses around assignment used as truth value (on my compiler at least)
Replace = with == to do the comparison instead of the assignment.
I remember once I've seen somebody writing C++ code like this:
if (something is true)
for (int i = 0; i < max; i++) {
//do something
line 1;
line 2;
line 3;
....
....
}
else
....
It works the same as the following code:
if (something is true) { //note the bracket here
for (int i = 0; i < max; i++) {
//do something
line 1;
line 2;
line 3;
....
....
}
}
else
....
I'm wondering if the compiler treated the for loop block as one line nested within the if clause? Can the multiple lines of code within bracket always be treated as one line? I can't quite understand how does the compiler parse and analyse this.
This is indeed correct code, although it may easily confuse readers. The if-statement considers the first following statement as it's then statement. Code between {} is usually considered a block or compound statement, containing the statements within it. Similarly, the for statement is considered one statement, including the loop body, which is the first statement to follow it (and can again be a block).
They are not really "lines" but rather statements. For instance your
line 1;
line 2;
line 3;
could be rewritten as and would be just as valid as:
line 1; line 2; line 3;
So the compiler is not really looking at lines but rather statements.
A single statement as defined by the grammar is considered either (somewhat simplified):
1) a simple statement terminated by a semicolon (as above)
OR
2) as a statement-block which is one or more simple statements enclosed within brackets {}.
Your first case runs fine because the if statement without brackets considers the next single statement(for loop)as a part of its body to be executed. The body of the for loop is a part of the loop itself.
If there had been no brackets for the loop itself, then only the first statement of the loop would have been executed.
{} defines a compound statement or block.
With the introduction of control structures we are going to have to
introduce a new concept: the compound-statement or block. A block is a
group of statements which are separated by semicolons (;) like all C++
statements, but grouped together in a block enclosed in braces: { }:
From cplusplus.com: Control Structures
The if control structure is defined as follows:
if (condition) statement
That statement can be defined as a single instruction/statement, or a compound statement. Either way, it's the next statement to be executed.
for (;;) statement is a special type of control structure called an iteration structure.
Therefore,
//The control structure is going to apply to the next statement
if (condition)
for (;;) //This for loop is the next statement. It applies to the next statement.
{
//The next statement is a compound statement.
}
Yes if there are no brackets after the if-statement it will just process the next line if the conditions are true. Since the next line was a for statement, it treats it as one command.
While I was looking at the library code, I found the below line
int number = config.nodes,i,fanout=numP/2;
I assume config is a pointer to something, but can there be commas in the statement? and make assignment like that?
This declares three variables. It's the same as:
int number = config.nodes
int i;
int fanout = numP/2;
Please note that commas are handled specially in declarations (and argument lists), C++ also has a "comma operator" which is not being used here.
It's valid, number is not being assigned the entire line you see though.
i and fanout are 2 other integers also being created at that time, fanout is also being initialized at this time.
That one line is equivalent to:
int number = config.nodes;
int i;
int fanout = numP/2;
Its basically many declaration:
int number = config.nodes;
int i;
int fanout=numP/2;
A more recognizable way to write this would be:
int number, i, fanout;
number = config.nodes;
fanout = numP/2;
I personally would never write something like your example because it takes too long for the reader to work out what's going on.
I have the following additions:
1) The whitespace is always ignored by the C++ compiler. So,
int number = config.nodes,i,fanout=numP/2;
is equivalent to
// declaring three variables number, i and fanout
int number=config.nodes, i, fanout = numP/2;
The comma here is to tell the compiler that i have more than one variable to declare. So, number will be initialized with config.nodes. If config is a pointer (as you mentioned above), then you cannot access member variables using . operator. You have to use -> instead of ..
2) The following line has different semantic:
// only one variable will be declared, which is number
int number = (config.nodes,i,fanout=numP/2);
Inside the parenthesis is an expression and the comma here is a comma operator. In this case, config, i, fanout and numP are previously defined. The value of comma operator is the value of last expression fanout=numP/2.
this is probably a very noob question but I was what the result of this would be:
int someVariable = 1;
while (callFunction(someVariable));
if (someVariable = 1) {
printf("a1");
} else {
printf("a2");
}
callFunction (int i) {
while (i< 100000000) {
i++;
}
return 0;
}
so when you hit the while loop
while (callFunction(someVariable));
does a thread wait at that loop until it finishes and then to
if(someVariable == 1) {
printf("a1");
} else {
printf("a2");
}
or does it skip and move to the if condition, print "a2" and then after the loop has finished goes through the if condition again?
UPDATE: This isn't ment to be valid c code just psuedo, maybe I didn't word it right, basically what I'm trying to figure out is what the different between a loop like while (callFunction(someVariable)); is vs
while (callFunction(someVariable)){}
i also changed the bolded part in my code i.e ** int someVariable = 1; **, I was doing an endless loop which wasn't my intention.
The code inside a function is executed sequentially, by a single thread. Even if you send an other thread to your function it will execute it sequentually as well.
This is true to 99% of programming languages now days.
UPDATE
basically what I'm trying to figure out is what the different between a loop like while (callFunction(someVariable)); is vs while (callFunction(someVariable)){}
No practical difference. ; delimits an empty statement, { } is a scope without statements. Any compiler can be expected to produce identical code.
Of course, if you want to do something in each iteration of the loop, { } creates a "scope" in which you can create types, typedefs and variables as well as call functions: on reaching the '}' or having an uncaught exception, the local content is cleaned up - with destructors called and any identifiers/symbols use forgotten as the compiler continues....
ORIGINAL ANSWER
This...
callFunction(int i){
while (i< 100000000){
i++;
}
return 1;
}
...just wastes a lot of CPU time, if the compiler's optimiser doesn't remove the loop on the basis that it does no externally-visible work - i.e. that there are no side-effects of the loop on the state of anything other that "i" and that that's irrelevant because the function returns without using i again. If always returns "1", which means the calling code...
while (callFunction(someVariable));
...is equivalent to...
while (1)
;
...which simply loops forever.
Consequently, the rest of the program - after this while loop - is never executed.
It's very hard to guess what you were really trying to do.
To get better at programming yourself - understanding the behaviour of your code - you should probably do one or both of:
insert output statements into your program so you can see how the value of variables is changing as the program executes, and whether it's exiting loops
use a debugger to do the same
Your code contains an endless loop before any output:
while (callFunction(someVariable));
Did you mean for the ; to be there (an empty loop), or did you
mean something else? Not that it matters: callFunction
always returns 1, which is converted into true. (If you
really want the loop to be empty, at least put the ; on
a separate line where it can be seen.)
If you do get beyond the while (because you modify some code
somewhere), the if contains an embedded assignment; it's
basically the same as:
if ( (someVariable = 1) != 0 )
Which is, of course, always true. (Most C++ compilers should
warn about the embedded assignment or the fact that the if
always evaluates to true. Or both.)
If your loop completes (it would be sequentially yes, if you fix it), it will print 'a1', since you're doing an assignment in the if, which will always return 1, which evaluates to 'true' for conditionals.