I am not really sure how or why this works:
#include <stdio.h>
#include<stdlib.h>
#include <limits.h>
#include <iostream>
using namespace std;
int main() {
int min = INT_MAX, min_index;
cout << min <<"\n";
cout << INT_MAX << "\n";
cout << min_index <<"\n";
system("pause");
return 0;
}
There is actual output for min, INT_MAX, and min_index
I know that INT_MAX is part of the limits.h and so min and INT_MAX are the same but min_index isn't given a value why does it display a value.
C++ isn't a memory-safe language. There's no guarantee that a variable has been a assigned a value before it's used.
What you're seeing as the printed value of min_index, is the value in the memory of min_index that just so happened to be left from the last time the memory was set previously.
Reading from such an initialized variable is "undefined behaviour", in that each invocation of this program will likely lead to a different, unexpected result (depending on what was last using the memory that eventually got allocated for min_index).
In a language like C and C++, when you define a variable, like:
int x;
a small block of memory is allocated to the variable. However, we have only declared the variable, and not initialized it, which means that the block of memory that has been allocated to the variable still contains some value that has been left over from previous programs and operations. That value is called a garbage value. This may lead to erroneous results in programs.
To avoid this, declare and initialize variables like this:
int x = 0;
Source: What do you mean by a garbage value in a variable?
See also: How does an uninitiliazed variable get a garbage value?
Because $min_index is not initialized to a specified value but it is assigned to a memory location. If you print min_index without initializing it first, the values on that memory location will be interpreted as data of the type of min_index.
Therefore it is always recommended to initialize a variable, because you will never know, what the value of that memory location is.
you cant initialize min= int_max. the value is showing due to garbage value
Related
I'm playing with a function to get used to some C++ syntax.
Now I think, I might have misunderstood:
I'm writing to a static (?) array I had defined as myArray[0] for experimenting.
So it seems NOT to be static, but sizeof(myArray) always returns 0 (?)
but I can find mem address for each item (while I have no idea, how to get the number of items this way).
The other thing I don't understand, is why I can write myInt = myFloat?
So, what IS a static array? And should I better use <vector> for an array of undefined length?
(You could find the whole code here int2bin main.cpp)
#include <iostream>
//#include <regex>
int main()
{
while(true) {
//VARS
unsigned int arrBin[0], intNum; //working, if set [0]! NOT static???
unsigned int *pArr0 = &arrBin[0];
unsigned int *pArr1 = &arrBin[1];
std::cout << sizeof(arrBin) << '\n'; // 0 => sizeof() here items and not mem space?
std::cout << pArr0 << '\n';// 0x7fff12de6c38
std::cout << pArr1 << '\n';// 0x7fff12de6c3c
int i;
float refNum;
std::cout << "\n\nEnter a number to convert: ";
// GET INPUT
std::cin >> refNum; // float
intNum = refNum; // get int of the dec for comparing. Why does this "int = float" work???
unsigned int arrBin[0]
The size of an array variable must not be 0. The program is ill-formed. Don't do this.
unsigned int *pArr1 = &arrBin[1];
Here, you use subscript operator beyond the bounds of the array (beyond one past last element), so the behaviour of the program is undefined. Don't do this.
(while I have no idea, how to get the number of items this way).
The number of items is 0 (or would be if that was allowed in the first place).
The other thing I don't understand, is why I can write myInt = myFloat?
You haven't even declared such identifiers.
I'm writing to a static (?) array I had defined as myArray[0] for experimenting.
By 'static' you probably mean 'fixed-sized'. static means something totally different, see https://www.geeksforgeeks.org/static-keyword-cpp/.
So it seems NOT to be static
It is not static, hence, it's not surprising that it's not static.
but sizeof(myArray) always returns 0
Its size is 0, as the size of 0 was specified. While this is not supported by the standards, it's possible that some compilers allow it.
but I can find mem address for each item (while I have no idea, how to get the number of items this way).
&arr[i] yields the address.
The other thing I don't understand, is why I can write myInt = myFloat?
Integer numbers are always real numbers, but real numbers are not always integer numbers. So, how would you store 0.5 as an integer? You could cast it or you could round it.
So, what IS a static array?
In the link I have provided you, it is mentioned that static variables in a function are variables for whom memory is allocated for the whole duration of a program. Hence, a static array is an array declared with the static keyword for which space are allocated for the whole lifecycle of your program. No such array was declared in your function.
And should I better use for an array of undefined length?
This is opinionated. You could create a pointer and navigate to items using pointer arithmetics, achieving the same behavior as with arrays, but without the length being fixed and with a slightly different syntax. Or you could use a library, a vector or whatever fits your task and taste.
For some reason, the value of final_sum is 16 but I didn't initialize a value for that variable, why's that? Isn't supposed to start with 0?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int n, sum, final_sum;
cout<<"ff: "<<final_sum<<endl;
cout<<"Input the value for n: ";
cin>>n;
for(int i=1; i<=n; i++){
sum += i;
final_sum += sum;
cout<<"sum: "<<sum<<endl;
cout<<"final sum: "<<final_sum<<endl<<endl;
}
return 0;
}
Isn't supposed to start with 0
No, its initial value is undefined. See https://en.cppreference.com/w/cpp/language/default_initialization
the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.
If you do
int final_sum{};
Or
int final_sum = 0;
You will have a 0 in your variable.
I suggest you to use -Wuninitialized (or better -Wall). The compiler will raise a warning if you forgot and initialization
If you don't initialize a variable before reading/using it, its undefined behavior. Its value can then be anything, it's unpredictable and always a bad idea. Use
int final_sum = 0;
to initialize it.
From documentation:
The value in an uninitialized variable can be anything – it is
unpredictable, and may be different every time the program is run.
Reading the value of an uninitialized variable is undefined behaviour
– which is always a bad idea. It has to be initialized with a value
before you can use it.
and
The only place where they are useful is when you are about to read the
variable in from some input stream.
Edit : Some may ask "Why my variable still print 0 even though I haven't initialize it?"
From this post :
That is because variables with automatic storage duration are not
automatically initialized to zero in C++. In C++, you don't pay for
what you don't need, and automatically initializing a variable takes
time (setting to zero a memory location ultimately reduces to machine
intruction(s) which are then translated to electrical signals that
control the physical bits).
So when you do :
int final_sum;
The final_sum is just being reserved a memory location, and anything currently inside that location will be printed out by cout. It just happened that there's a big 0 in that spot.
More info : (Why) is using an uninitialized variable undefined behavior?
Declaring the variable globally does the job
int final_sum;
int main() {
your code ...
}
is the same as
int final_sum = 0;
int main() {
your code here ...
}
However, you probably don't want to use global variables and it is always recommended to initialize variables with some value.
I'm learning C++.
And I thought that Array[i]=*(Array+i) .
In the code below, if we remove the phrase within the comments(For Loop)
*(x+1) Not equal to When (For-Loop) Existed.
my compiler is mingw.
main()
{
int x[10];
//////////////////////////////////////////////////////////////////
for(int i=0;i<=9;i++)
cout<<"x"<<"["<<i<<"]"<<"--->"<<x[i]<<endl;
//////////////////////////////////////////////////////////////////
cout<<*(x+1);
}
I expected the output of *(x+1) to be the same before and after remove for.
thanks and sorry about my grammar.
The problem is, x in an automatic local variable and never initialized. The contents of the array members are indeterminate.
You cannot have any expected value there. Every time you execute, you'll get indeterminate values.
I compiled the following code using g++
#include <iostream>
int main()
{
double res;
std::cout << res << std::endl;
return 0;
}
That gave the following result
g++ foo.c
./a.out
0
But after a small change
#include <iostream>
int main()
{
std::string input;
double res;
std::cout << res << std::endl;
return 0;
}
It became
g++ foo.c
./a.out
2.0734e-317
Why are the results different and why the number 2.0734e-317?
Your code invokes undefined behaviour. Since automatic variables of built-in types are not deafult-initialized unless specifically aksed, value for variable res is undefined in your code. It can be anything.
Why you have different value their based on different code structure is understandable - since no one is setting the value for the variable, you are left with whatever is left in the stack memory after previous calls. Pure random.
In particular, in the former example, the stack memory is not used at all before you declare your res variable. As a result, you use untouched stack memory, which is 0 initialize. In the latter case, you have already defined string variable, and called it's constructor. Constructor used stack memory for it's own purpose, and left those values there. Now the res variable is constructed in used stack memory, and you see some random values there.
It's arbitrary.
You did not initialise your variable. It has an unspecified value.
Therefore, reading its "value" has undefined behaviour. Anything can happen.
Not only can you get any value (due to internal assumptions that you cannot rationalise about from outside of the black box of the compiler implementation), but you could also/instead open a black hole or kill my cat, and I would not be terribly happy about either of those outcomes.
You are outputting an uninitialized variable. So it's value can be anything.
Iam trying to compile this program but i get warning and when i run vc++ 2010 debugger pops up : (
Here is my code :
#include <iostream>
using namespace std;
int num;
int min(int mas[])
{
int i,minn,index; /* But I have declared them : (((( */
for(i=0;i<num;i++)
{
if(mas[i]!=0)minn=mas[i];
break;
}
if(i==num) return 0;
for(i=0;i<num;i++)
if(mas[i]!=0 && minn>mas[i])
{
minn=mas[i];
index=i;
}
mas[index]=0;
return minn;
}
int main()
{
cin>>num;
int *array=new int[num]; int tmp;
tmp=min(array);
}
and Here is a compiler log :
prog.cpp: In function ‘int min(int*)’:
prog.cpp:6: warning: ‘index’ may be used uninitialized in this function
prog.cpp:6: warning: ‘minn’ may be used uninitialized in this function
What i am doing wrong ? or its is compiler bug ? :)
Thank you :)
You have declared them, but not initialized them. Simply write int minn = 0, index = 0; to avoid the warning. If you don't initialize a variable, its default value is whatever was at that location in memory already; usually garbage.
The thing is, if num is negative, then neither of the for loops in your min() function will execute, and so minn and index will not have been assigned values. The if(i == num) test also won't break out of the function and prevent this from happening. So the last two lines of the function will have completely undefined results.
Sometimes there really isn't a path for the variables to be used uninitialized, though; sometimes the compiler just isn't quite smart enough to figure out all the subtleties. Just give them an initial value to avoid the warning.
Declaration != initialization. When you declare them the variables have random values. Just initialize them to sensible values like -1 for index and minn to a INT_MAX.
But you haven't initialized them : ))))
EX: int i,minn=0,index=0; Imagine that you pass num that equals 0, at the end you would be returning uninitialized value of minn and just before that you would set mas[unknown_number]=0; which will probably cause your app to crash since you will be referencing memory that is most likely beyond your scope. You should do a check in the beggining like if(num<1)return -1;
Suppose the entire array you pass in is 0. Both loops short-circuit and never execute, both minn and index are uninitialized.
Now if this happens, what should be happening? Set the variables to the values that accomplish just that.
As you say in your comment, yes, you have declared your variables, but you haven't initialized them. Initializing a variable means giving it a value. So in this case, you have told the compiler that you want to create three integers, but you haven't told it what values you want to store in those integers. That would be ok if, for every possible path through your function, index and minn were guaranteed to be given a value, but the problem here is that there is a path through your function where minn and index will never be initialized. First of all, here:
for(i=0;i<num;i++)
{
if(mas[i]!=0)minn=mas[i];
break;
}
If you have an array of zeros, then minn is never initialized to a value.
Then further down:
for(i=0;i<num;i++)
if(mas[i]!=0 && minn>mas[i])
{
minn=mas[i];
index=i;
}
first of all, if you had an array of zeros, well what is the value in minn? There is no value. You are asking the compiler to compare mas[i] to a number which doesn't exist. Furthermore, what if mas[i] is always equal to zero? Well now you don't initialize minn or index. Yet at the end of the function, you are attempting to use the value of index to get an integer from the array amd then you return minn (which still equals nothing).
That's the problem you're getting from the compiler. It can see this potential outcome and is warning you that your function can be broken due to these integers never getting a value. To fix it, do what the other lads have suggested and let index and minn equal zero at the start.