+ 26
C++ variable
for example look at this code that save the variable named (a)'s digits in array named b👇 https://code.sololearn.com/clZ776WVVxfI/?ref=app if you run it the output is "no output" but if you use endl after b[x] it output correct result i wrote a code yesterday and run it but it results nothing same this code , i looked about 1hours where is the problem but i couldn't find the problem today i wrote another simple code but it results like that Do i make mistakes ?
16 Respostas
+ 11
AliR૯za No, not in C++. When you declare a variable without initializing it, it will keep whatever value used to be stored at that point in memory before it.
int main()
{
{
int x = 1000;
} //x goes out of scope, and can't be used beyond this point
{
int y;
cout << y; // The compiler may use the same location to store both x and y for efficiency, so this might output 1000. However you can't rely on it.
}
}
EDIT: This outputs 16 11 for me. So, in short, an unitialized variable contains garbage.
https://code.sololearn.com/cn5NkZmKpbfK/?ref=app
+ 20
Hatsy Rei , Vlad Serbu
Right , this discuss solved my recently problems in c++
i didn't gave value to variables when i would gave it 0
Thank you
+ 18
https://code.sololearn.com/cyWn2E1G5sPi/?ref=app
Hatsy Rei ,Vlad Serbu
but why in this code it give x zero value ?
+ 16
Vlad Serbu , Hatsy Rei right but is it correct that when we doesn't give value to x , compiler give it 0 ?
+ 11
AliR૯za C++ does not automatically initialize variables to 0 for you.
+ 8
Exactly as stated by Vlad Serbu. You were using an uninitialised variable, the program probably did not write proper contents to array b. Adding std::endl flushes the output stream, which would give you a wrong output anyways.
+ 8
It is not stated in the C++ standard. You can get 0 by pure luck - Whatever is left behind in the memory address of what happens to now be the address of x. I'm getting 8 on my side.
+ 4
Interesting. It's worth noting that you're relying on undefined behavior, and that, if you write "x=0" instead of "x", it works as expected, without a need for std::endl.
+ 2
Like most user sayed, in standard its not definited a default value for unitialized local not-static variable (differently from global and static variable where uninitialized value must be 0 by standard)
+ 2
microsoftsolutions.net
0
can you speak chinese , i can not understand
0
ali raza you are wrong in coding declaration
0
bos ablas español
0
Variables are the names like
A = 10;
Here A is a variable and 10 is the value of it.
Its pretty simple bro.
- 2
a=2;
b=3;
x=0;
(++b,a)
find the value of x
- 3
我就想知道你们说的我为啥看不懂