In the following program:
#include <iostream>
using namespace std;
int main(){
int i = 99;
for(int i = 1; i <= 10; i++)
{
cout << i << endl;
}
cout << endl << endl;
cout << i << endl;
return 0;
}
I am not getting an error on compilation.
My question is why this is happening.
The int variable i was declared twice. The first time i was declared in the main() function and thus its scope will be this whole main() function including the for loop. The second time i was declared with the for loop and thus its scope will be only the for loop. So, now inside the scope of the for loop there exists two int variablesi. Shouldn't this be a cause of error? And if not why?
Second thing is the output I am getting:
1
2
3
4
5
6
7
8
9
10
99
I also don't understand the output. Why after the execution of the for loop, the value of i that is being printed is 99 and not 10.
You can define variables with the same names in different scopes. The first variable i is defined in the scope of the main function. In the loop there is another implied nested and anonymous scope for the variables you declare for the loop.
For the compiler, the code
for(int i = 1; i <= 10; i++)
{
cout << i << endl;
}
is more or less equivalent to
{
int i;
for(i = 1; i <= 10; i++)
{
cout << i << endl;
}
}
Related
I am practice with C++ and I see some problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 2;
{
cout << a;
cout << "\n";
float a = a / 2;
cout << "a= a/2 = ";
cout << a;
}
cout << "\n";
a = 2;
{
cout << a;
cout << "\n";
float b = a / 2;
cout << "b= a/2 = ";
cout << b;
}
}
This return:
2
a= a/2 = 0
2
b= a/2 = 1
I want to know why a = a/2 = 0 ?
Thank you
This is a subtle error. Look at this code:
int a = 2;
{
float a = a / 2;
}
Outside of the curly braces, the name a refers to int a, the integer declared up top. But inside the curly braces, once you reach the line in which float a is declared, the name a refers to float a inside the braces rather than int a outside the braces.
This is a problem because the line
float a = a / 2;
means "create a new variable named a of type float. Oh, and it needs an initial value. That's okay! Give it the value of float a, divided by two." See the problem here? The variable a is being initialized in terms of itself, so when a / 2 is computed a has not been initialized and the results are undefined.
To fix this, simply give float a a new name.
Because you are actually using declared, but never initialized variable when you stated float a = a/2. My computer prints 4.49985e-039 but that could be any number.
You are confusing yourself because you have two int & float variable with same name. Better to choose your name of the variable carefully or you have to track your code to see which is indicating which.
I'll comment on the each line which variable a has been used.
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 2; // int a declared in main scope used;
{
cout << a; // int a declared in main scope; since there is no a declared in local scope.
cout << "\n";
float a = a/2; // block scope variable a used without initialization to initialize itself. UB.
cout << "a= a/2 = "; // block scope variable used
cout << a; // block scope variable used
}
cout << "\n"; a = 2; // int a declared in main scope; Since it's block scope is within main scope only.
{
cout << a; // int a declared in main scope; since no a has been declared in local scope
cout << "\n";
float b = a/2; // int a declared in main scope; since no a has been declared in local scope
cout << "b= a/2 = "; // int a declared in main scope; since no a has been declared in local scope
cout << b;
}
}
I'm just a beginner at C++ and I came across this instance.
#include <iostream>
using namespace std;
int main(){
int c = 3;
int d = c++;
if (c++ == 4 && d == 3)
cout << "1: " << c << " " << d << endl;
if (++c == 5 && d-- == 3)
cout << "2: " << c-- << " " << d << endl;
cout << "3: " << c << " " << d << endl;
}
So in this case, the output would be:
1: 5 3
3: 6 3
And what I understand from this is that the variables would still be updated even if they are being called for an increment in the if statement.
Now I came across this:
#include <iostream>
using namespace std:
int main(){
for (int i= 1; i <= 10; ++i){
cout << i ;
break
}
}
And even though its being incremented it's only returning 1. So I thought that maybe the 2nd time it goes through the loop (after removing the break of course) it would return 3, cause then it would have passed through ++i twice, but it's still 2. I don't understand. So my question is why would there be an instant increment in the if statement but there is none when ++i exists in the for loop ?
EDIT: just fixed a typo. I was supposed to type semicolon but put a comma instead :b
EDIT: added a more straightforward question as some are wondering what I am asking.
A for statement has 4 parts, they are not in the order they are executed.
for ( init-statement condition; iteration_expression) statement
Is defined as equivalent to
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
Except that
Names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope (which is also the scope of statement).
continue in the statement will execute iteration_expression
Empty condition is equivalent to while(true)
I am learning c++ and I came across a really odd phenomenon in a program. I haven't seen any documentation on this problem. Why is that when I initialize a variable inside of a conditional statement it isn't recognized outside of it? Is the variable local to the conditional statement?
Here is an example:
#include "stdafx.h"
#include <iostream>
using namespace std;
/*scope / range of variables */
int global;
int main()
{
int local = rand();
cout << "value of global " << global << endl;
cout << "value of local " << local << endl;
int test = 10;
if (test == 0)
{
int result = test * 10;
}
cout << "result :" << result << endl;
return 0;
}
In this case result is undefined. Can someone please explain what is going on?
As pointed out in the comments, your declaration of result is local inside the if() blocks scope you provided:
if (test == 0)
{ // Defines visibility of any declarations made inside
int result = test * 10;
} // ^^^^^^
Hence the statement
cout << "result :" << result << endl;
would lead to a compiler error, since result isn't visible for the compiler at this point outside that scope.
But even if you declare result correctly outside of the scope block, your logic
int result = 0; // Presumed for correctness
int test = 10;
if (test == 0)
{
result = test * 10; // Note the removed declaration
}
doesn't make much sense, since test was given the value 10 immediately before testing it against the value 0 in your your if() statements condition, and the condition never would become true.
For some unknown reason this simple code runs, does what it's expected to do and then crashes the run. I am using NetBeans IDE, which overlapped my arrays before (tends to be buggy), so I was wondering if someone gets the same error - that would mean I certainly have to change the IDE environment.
#include <iostream>
using namespace std;
int main ()
{
int first[4][4];
for (int a = 0; a < 5; a++)
{
for (int b = 0; b < 5;b++)
{
cout << a << " " << b << " ";
if (first [a][b] != 0)
{
first[a][b] = 0;
}
cout << first[a][b] << " ";
}
cout << endl << endl << endl;
}
return 0;
};
here you are declearing a array with 4 indexes.In c/c++ index number starts at 0.
In your code you are saying :
int first[4][4];
that means indexs are : 0 1 2 3.Array length or total index are 4.
But in for loop you are saying
for (int a = 0; a < 5; a++) {
....
}
so you are trying to access index number 0 1 2 3 4 respectively.But remember you don't have index number 4.That is why it should give array index out of bound error.
Also at the end of main function you are using a semicolon.remove that
main () {
....
};
Hope this solves the problem.From next time Please try to provide details about the errors your IDE is giving you as it will be easier for the people who are giving answer.
I've encountered a problem while trying to create a code which converts decimal numbers to binary, using functions. At first I created the code using only main function and it worked fine, but decided to modify it to use function. I believe code is written right, however when I try to cout my answer I get a big number like 115120160758866453687091316369641637416.
This is the code
#include <iostream>
#include <math.h>
using namespace std;
int* unsigned_dec(int dec_M) { //function for converting absolute part of numbers
int bin[8] = { 0,0,0,0,0,0,0,0 };
int ind = 7;
int arr_ind = 0;
for (int base = (int)abs(dec_M); base > 0; base = base / 2) {
if (base % 2 == 0) {
bin[arr_ind] = 0;
ind--;
}
else {
bin[arr_ind] = 1;
ind--;
}
arr_ind++;
}
return bin;
}
int main() {// main function
int dec_N;
cin >> dec_N;
int* bin_main = unsigned_dec(dec_N); //we are not sure if we are assigning the returned value of function to array in correct
for (int i = 0; i <= 7; i++) {
cout << bin_main[i];
}
cout << endl;
return 0;
}
then I tried to change the cout code to
cout << bin_main[0] << bin_main[1] << bin_main[2] << bin_main[3] << bin_main[4] << bin_main[5] << bin_main[6] << bin_main[7] << endl;
And this worked fine.
Then I wrote the same 2nd variant of cout in other way
cout << bin_main[0];
cout << bin_main[1];
cout << bin_main[2];
cout << bin_main[3];
cout << bin_main[4];
cout << bin_main[5];
cout << bin_main[6];
cout << bin_main[7];
cout << endl;
and my code started to cout the same strange number. I think that all 3 ways of couts are almost the same (especially 2 and 3), but don't understand what makes it not to work.
int bin[8] = { 0,0,0,0,0,0,0,0 };
is allocated on stack. You should either allocate bin on heap
auto bin = std::unique_ptr<int, std::default_deleter<int[]>>(new int[8]);
or even better, use std::vector
you are returning pointer to local array of intbin[] in unsigned_dec. This array on stack of function unsigned_dec will get invalidated once another function from main gets called i.e cout operator .
As others have already mentioned: A function should never return a pointer to a local variable. Local variable is not valid when the function returns.
A better way is to use a vector and just make the function return the vector.
Something like:
#include <iostream>
#include <math.h>
using namespace std;
//function for converting absolute part of numbers
vector<int> unsigned_dec(int dec_M) {
vector<int> bin; // Create a vector
bin.resize(8, 0); // Fill it with 8 elements initialized to zero
int arr_ind = 0;
// Note: added check for arr_ind being valid
for (int base = (int)abs(dec_M); base > 0 && arr_ind < 8; base = base / 2) {
if (base % 2 == 0) {
bin[arr_ind] = 0;
}
else {
bin[arr_ind] = 1;
}
arr_ind++;
}
return bin; // Return the vector
}
int main() {
int dec_N;
cin >> dec_N;
vector<int> bin_main = unsigned_dec(dec_N);
for (int i = 0; i < bin_main.size(); i++) {
cout << bin_main[i];
}
cout << endl;
return 0;
}