Declaring and Initializing C++ Static variables - c++

Note: This is coming from a beginner.
Why does the first one outputs 333 and the second one 345 ?
In the second code does it skips over the declaration? I mean it should initialise the "j" variable again like in the first one.
int main() {
static int j =12;
for(int i=0; i<=2; i++) {
j = 2;
j += 1;
std::cout<<j;
}
return 0;
}
int main() {
for(int i=0; i<=2; i++) {
static int j = 2;
j += 1;
std::cout<<j;
}
return 0;
}

static variables are only initialized once (when first used). After that, it behaves as if it is declared somewhere else (I mean, the initialization is ignored). In the second main, the initialization static int j = 2; is executed only the first time, after that, you are incrementing it sequentially (i.e. 2,3,4...)
In the first loop, you set it's value on each iteration, which is not the same as initialization, so it can be run multiple times.

Related

How does C++ while code including two integers operate step by step?

I am quite new to C++ programming, I have reviewed while loops in python before however the two integers confuse me here. I would be very happy if you can explain to me how this while loop operates step by step.
#include<iostream>
using namespace std;
int main() {
int i;
int j;
while(i<10 || j < 5) { // i kucuk ondan kucuk oldu surece {} icerisindeki islemler surekli olarak while() loopu ile tekrarlancak
cout<<"i: "<<i<<" "<<"j: "<<j<<endl;
i = i + 1; // eger bu kod olmaz ise, sonsuza dek i degerine basacak
j = j + 1;
}
return 0;
}
#include<iostream>
using namespace std;
int main() {
/* You should first give a starting value
to the I and j, otherwise they
will get a random number and your while won't work*/
int i=0;
int j=0;
/* so as the word says "while" - while (something here is true)do the
following code between the starting
brackets and the finishing brackets. When it's not True skip the loop and go to the next line, in this example we will go to return 0 */
/*The value of i is 0 and the value of j is 0, and we first check if 0(i)<10 that's true next we check the other one
if 0(j) < 5 yes do the following block*/
/* the || mean "or' if either one of them
is true do the following block of code between the brackets*/
while(i<10 || j < 5) {
//we print
cout<<"i: "<<i<<" "<<"j: "<<j<<endl;
//we are incrementing the values of i and j for 1;
i = i + 1;
j = j + 1;
/*so what happens now it jumps again to the while
and checks if the statement is true, now i = 1 and j = 1;
and this runs until i is 10 because only then the i won't be lesser then
10 and j won't be lesser then 5 it will be false*/
*/
}
//close the program
return 0;
}
Hope I was clear!
You don't declare variables in Python. A "variable" is created when you first assign a value to a name. So you can't have uninitialized variables in Python.
That is not the case in C and C++. This code is declaring the i and j variables, but not assigning any values to them before trying to use them in the while loop. So your code has undefined behavior, as the variables contain whatever random values happened to already be present in memory where they get allocated.
You need to initialize the variables before your loop tries to evaluate them:
int i = 0;
int j = 0;

Please explain the scope of for loop indices

I just want to confirm a suspicion I have about loop indexes. I am using c++.
I have two for loops in my code. For one I declared my index outside of the loop, i.e
int i;
for(i = 0; i < n; i++){
. . .
}
cout << i <<endl;
And then I have later:
for(int j = 0; j<n; j++){
. . .
}
cout << j <<endl;
In the first case I see that some random number is outputted. In the second case, I get an error message about -fpermissive or something like that. I just want to confirm that the index goes out of scope whenever the loop ends, because that seems to be what is happening.
I was trying to use the index for something later on, I guess I just have to put a second index in the loop to increment as i or j do, and then I can use this value later. i.e.:
int index = 0;
for(int j = 0; j<n; j++){
. . .
index ++;
}
cout << index <<endl;
Would someone confirm this for me?
The first example::
http://codepad.org/L5VErMAh
int main( void )
{
int i, n = 10 ;
for(i = 0; i < n; i++){
// do something useful. . .
}
cout << i <<endl;
return 0 ;
}
Output:: 10
Explanation:: The scope of i and n is global for the for loop. So, they don't go invalid or undefined after the execution of for loop.
The second example:: http://codepad.org/iqNtQ1Ok
int main( void )
{
int n = 10 ;
for(int j = 0; j < n; j++){
// do something useful. . .
}
cout << j <<endl;
return 0 ;
}
Output:: name lookup of 'j' changed for new ISO 'for' scoping
Explanation:: The scope of n is global for for loop but as the j is declared inside the for loop, its scope and lifetime is local for the for loop. That means, the j will be and is destroyed after the execution of for loop. That's why, the error.
The third example:: I think, you must have got the idea that it is pretty same as the first example.
Now for your doubt, "In the first case I see that some random number is outputted." No, that can't happen unless you are doing something wrong inside the for loop. You can post the first case for loop code and we can point you out the error.
In the first case, since j is declared outside the loop, the scope of i is even the outside of the loop. So,
cout<<i<<endl;
prints the value of n. The second case, j is declared in the loop. So the scope of j is only inside the loop; So you get the error.
So the first case itself you can use the value of i at later phases
#include<stdio.h>
main()
{
int i;
for(i=0;i<5;i++)
printf("%d\n",i);
return 0;
}
gave me an output of 5.
well this one will just print n
int i;
for(i = 0; i < n; i++){
//...
}
cout << i <<endl;//prints the value of n
and this one J is declared out of scope
for(int j = 0; j<n; j++){
. . .
}
cout << j <<endl; //the compiler asks: whats a j?
and the last one does the same as the first
int index = 0;
for(int j = 0; j<n; j++){
. . .
index ++;
}
cout << index <<endl;//still prints n

Does compiler detect false shared variable?

As i prepared some code sample for a small presentation of OpenMP to my teammate i found a weird case. First i wrote a classic loop :
void sequential(int *a, int size, int *b)
{
int i;
for (i = 0; i < size; i++) {
b[i] = a[i] * i;
}
}
A correct OpenMP usage of a for directive is simple. We just have to move int i declaration in for scope to make it private.
void parallel_for(int *a, int size, int *b)
{
#pragma omp parallel for
for (int i = 0; i < size; i++) {
b[i] = a[i] * i;
}
}
But when i wrote the following function, I expected i get a different result of the 2 other due to the shared int jI declared out-of the for loop scope. But using my test framework I don't see the error I expected, an incorrect value at the output of that function.
void parallel_for_with_an_usage_error(int *a, int size, int *b)
{
int j;
#pragma omp parallel for
for (int i = 0; i < size; i++) {
/*int*/ j = a[i]; //To be correct j should be declared here, in-loop to be private !
j *= i;
b[i] = j;
}
}
I have a complete source code for testing, it build with VS'12 and gcc (with C++11 enable) here http://pastebin.com/NJ4L0cbV
Have you an idea of what's the compiler do ? Does it detect the false sharing, does in move int j in the loop due to an optimization heuristic ?
Thank
In my opinion what might be happening is that compiler is doing some optimization. Since in the above pasted code (without cout), the variable j is not being anywhere other than inside the loop, the compiler can put the declaration of j inside the loop in the produced assembly code.
Another possibility is that the compiler might be converting the 3 statements inside the loop into one single statement, i.e. from
/*int*/ j = a[i]; //To be correct j should be declared here, in-loop to be private !
j *= i;
b[i] = j;
to,
b[i] = a[i] * i;
Compiler will do this optimization regardless of whether its an OpenMP code or not.

Noobish Array problems: Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted

I'll be pretty honest/upfront here- I'm both a noob to C++, to computer programming in general, and additionally, to this site as well. I'll just preface my question by saying that I did in fact look at other questions possibly related to my own, but it just felt like they were outside of my scope. With that said, here's my problem:
I get this error message:
"Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted."
Here's my code. It's just a basic little thing for some array practice. The function multiTable outputs a multiplication table:
#include <iostream>
#include <iomanip>
using namespace std;
void multiTable();
int main()
{
multiTable();
return 0;
}
//Prints a 9 by 9 multiplication table;
void multiTable()
{
const int row = 9, col = 9;
int arr[row][col];
for(int i = 1; i <= row; i++)
{
for(int j = 1; j <= col; j++)
{
arr[i][j] = j * i;
cout << setw(3);
cout << arr[i][j];
}
cout << endl;
}
}
I also want to mention that instead of the function call, had I just included all of the code contained within the function body in main, I don't get the run-time error. Why is it that when it's contained within a function, I get the runtime error, but when it's just in main, I don't get the error? And of course, what would I have to change in order for the function call to not produce the error?
Those are your problems: for(int i = 1; i <= row; i++) and for(int j = 1; j <= col; j++) array counting starts from 0. So your for loops should be like this (starting from 0 and omitting the = part from <=):
for(int i = 0; i < row; i++) and for(int j = 0; j < col; j++)

What does it mean when the first "for" parameter is blank?

I have been looking through some code and I have seen several examples where the first element of a for cycle is omitted.
An example:
for ( ; hole*2 <= currentSize; hole = child)
What does this mean?
Thanks.
It just means that the user chose not to set a variable to their own starting value.
for(int i = 0; i < x; i++)
is equivalent to...
int i = 0;
for( ; i < x; i++)
EDIT (in response to comments): These aren't exactly equivalent. the scope of the variable i is different.
Sometimes the latter is used to break up the code. You can also drop out the third statement if your indexing variable is modified within the for loop itself...
int i = 0;
for(; i < x;)
{
...
i++
...
}
And if you drop out the second statement then you have an infinite loop.
for(;;)
{
runs indefinitely
}
The for construct is basically ( pre-loop initialisation; loop termination test; end of loop iteration), so this just means there is no initialisation of anything in this for loop.
You could refactor any for loop thusly:
pre-loop initialisation
while (loop termination test) {
...
end of loop iteration
}
Some people have been getting it wrong so I just wanted to clear it up.
int i = 0;
for (; i < 10; i++)
is not the same as
for (int i = 0; i < 10; i++)
Variables declared inside the for keyword are only valid in that scope.
To put it simply.
Valid ("i" was declared outside of the loops scope)
int i = 0;
for (; i < 10; i++)
{
//Code
}
std::cout << i;
InValid ("i" does not exist outside the loop scope)
for (int i = 0; i < 10; i++)
{
//Code
}
std::cout << i;
It means that the initial value of hole was set before we got to the loop
That means loop control variable is initialized before the for loop .
For C code,
int i=0;
for( ; i <10 ; i++) { } //since it does not allow variable declaration in loop
For C++ code,
for(int i=0 ; i <10 ; i++) { }
You could omit any of the parameters of a for loop.
ie: for(;;) {} is about the same as while(true) {}
It means that the initial value of hole was set before we got to the loop.
Looks like a list traversal of some kind.
Suppose you wanted to
for (hole=1 ; hole*2 <= currentSize; hole = child)
But the value of hole just before the for loop was already 1, then you can slip this initilization part of the loop:
/* value of hole now is 1.*/
for ( ; hole*2 <= currentSize; hole = child)