C++ scalar variable set to zero value - c++

I'm using CodeBlocks 13.12, g++ compiler and my local variables are all being initializated to 0.
I would to know if there's a way to avoid the compiler to set 0 to all my variables. I would like to have garbage value in them.
For example:
#include <iostream>
using namespace std;
int main(){
int a, b;
cout << a << " " << b;
return 0;
}
The output is:
0 0
I don't want a and b to be zero. They should contain junk values.
Thanks in advance

The compiler behaves differently in this regard when building with/without optimization. I'm guessing you are building without optimization and that's why the compiler zero initializes variables.
But, when that is said; don't go around reading uninitialized variables. That is undefined behaviour. While you may often just get a 'garbage' value, the compiler is actually free to generate whatever code it wants when it sees that your program is undefined. This includes not emitting any code at all, emitting the code you expect as well as rewriting other parts of your program. Don't invoke undefined behaviour.
If you want a random value, use the <random> facilities - http://en.cppreference.com/w/cpp/numeric/random

Related

Differences in variable initialization location in C++ [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 6 months ago.
int main()
{
int a;
cout << a;
return 0;
}
I am wondering why the value 0 is being output. I thought if a variable is uninitialized, it would output a garbage value.
However, I also remember hearing that the default value of an integer is 0 so I am a bit confused.
Thanks
The default behavior of an uninitialized function scope (i.e., local) integer in C++ is for it to be indeterminate, which is fine; however if that value is used before it is defined it introduces undefined behavior, and anything could happen - demons could fly out of your nose.
This page on cppreference provides examples of default integer behavior.
On the other hand, all non-local, thread-local variables, not just integers, are zero initialized. But this case wasn't included in your original example.
(Side note: It is generally considered good practice to simply initialize variables anyway and avoid potential hazards altogether... Especially in the form of global variables. )
There are exceptions to best practice using global variables in rare special cases, such as some embedded systems; which initialize values based off of sensor readings on startup, or during their initial loop iteration... And need to retain a value after the scope of their loop ends.
I think you are not convinced with the answers/comments given, may be you can try the below code:
#include <iostream>
using namespace std;
int main(){
int a,b,c,d,e,f,g,h,i,j;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d<<endl;
cout<<e<<endl;
cout<<f<<endl;
cout<<g<<endl;
cout<<h<<endl;
cout<<i<<endl;
cout<<j<<endl;
return 0;
}
Well the reason being, a variable gets garbage value( a value unknown/senseless to program) is when someone runs a program, it gets loaded in some part of RAM. Now it all depends what values were previously set to certain location, may be some other program was there previously.
It just happen the your program has loaded into a that location where it happens to be 0 value in RAM and that's what you are getting in return.
It quite possible that if restart your system and try running the same program then you might get garbage value.
Above statements are valid for variables which doesn't get initialized by the compiler.

Pre increment and post increment when put together on a single variable like this (++i)++, it works in c++ but not in c

I initialized a variable i with a value 3, then put a statement (++i)++ in my code. But, in C, it is showing an error "lvalue required as increment operand". But, if I put this similar code in c++, it works and showing double increment with an output 5. However, one of my friends tried on his compiler using c and it gave an output 4.
//using c
#include <stdio.h>
int main()
{
int i=3;
(++i)++;
printf("%d",i);
return 0;
}
//using c++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i=3;
(++i)++;
cout << i << endl;
return 0;
}
I am using GNU GCC compiler.
This is known to be undefined behavior. Syntactically this program is correct in C++, and the compiler produces some binary code... but the standard allows it to produce ANY code, even something that returns 100 or formats your disk. In real situations you may observe very strange abnormal scenarios, for example the compiler can drop the whole code after your (++i)++ statement, because the standard allows it to do whatever it wants right after the program enters into the status of UB. In your case that would mean that there would be no output at all (or the program would print "Hello World" instead of the integer value).
I believe that you are just conducting an experiment. The result is: both your compiler and your friend's are correct.

How to make uninitiated pointer not equal to 0/null?

I am a c++ learner. Others told me "uninitiatied pointer may point to anywhere". How to prove that by code.?I made a little test code but my uninitiatied pointer always point to 0. In which case it does not point to 0? Thanks
#include <iostream>
using namespace std;
int main() {
int* p;
printf("%d\n", p);
char* p1;
printf("%d\n", p1);
return 0;
}
Any uninitialized variable by definition has an indeterminate value until a value is supplied, and even accessing it is undefined. Because this is the grey-area of undefined behaviour, there's no way you can guarantee that an uninitialized pointer will be anything other than 0.
Anything you write to demonstrate this would be dictated by the compiler and system you are running on.
If you really want to, you can try writing a function that fills up a local array with garbage values, and create another function that defines an uninitialized pointer and prints it. Run the second function after the first in your main() and you might see it.
Edit: For you curiosity, I exhibited the behavior with VS2015 on my system with this code:
void f1()
{
// junk
char arr[24];
for (char& c : arr) c = 1;
}
void f2()
{
// uninitialized
int* ptr[4];
std::cout << (std::uintptr_t)ptr[1] << std::endl;
}
int main()
{
f1();
f2();
return 0;
}
Which prints 16843009 (0x01010101). But again, this is all undefined behaviour.
Well, I think it is not worth to prove this question, because a good coding style should be used and this say's: Initialise all variables! One example: If you "free" a pointer, just give them a value like in this example:
char *p=NULL; // yes, this is not needed but do it! later you may change your program an add code beneath this line...
p=(char *)malloc(512);
...
free(p);
p=NULL;
That is a safe and good style. Also if you use free(p) again by accident, it will not crash your program ! In this example - if you don't set NULL to p after doing a free(), your can use the pointer by mistake again and your program would try to address already freed memory - this will crash your program or (more bad) may end in strange results.
So don't waste time on you question about a case where pointers do not point to NULL. Just set values to your variables (pointers) ! :-)
It depends on the compiler. Your code executed on an old MSVC2008 displays in release mode (plain random):
1955116784
1955116784
and in debug mode (after croaking for using unitialized pointer usage):
-858993460
-858993460
because that implementation sets uninitialized pointers to 0xcccccccc in debug mode to detect their usage.
The standard says that using an uninitialized pointer leads to undefined behaviour. That means that from the standard anything can happen. But a particular implementation is free to do whatever it wants:
yours happen to set the pointers to 0 (but you should not rely on it unless it is documented in the implementation documentation)
MSVC in debug mode sets the pointer to 0xcccccccc in debug mode but AFAIK does not document it (*), so we still cannot rely on it
(*) at least I could not find any reference...

What happens to uninitialized variables? C++ [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 6 months ago.
int main()
{
int a;
cout << a;
return 0;
}
I am wondering why the value 0 is being output. I thought if a variable is uninitialized, it would output a garbage value.
However, I also remember hearing that the default value of an integer is 0 so I am a bit confused.
Thanks
The default behavior of an uninitialized function scope (i.e., local) integer in C++ is for it to be indeterminate, which is fine; however if that value is used before it is defined it introduces undefined behavior, and anything could happen - demons could fly out of your nose.
This page on cppreference provides examples of default integer behavior.
On the other hand, all non-local, thread-local variables, not just integers, are zero initialized. But this case wasn't included in your original example.
(Side note: It is generally considered good practice to simply initialize variables anyway and avoid potential hazards altogether... Especially in the form of global variables. )
There are exceptions to best practice using global variables in rare special cases, such as some embedded systems; which initialize values based off of sensor readings on startup, or during their initial loop iteration... And need to retain a value after the scope of their loop ends.
I think you are not convinced with the answers/comments given, may be you can try the below code:
#include <iostream>
using namespace std;
int main(){
int a,b,c,d,e,f,g,h,i,j;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d<<endl;
cout<<e<<endl;
cout<<f<<endl;
cout<<g<<endl;
cout<<h<<endl;
cout<<i<<endl;
cout<<j<<endl;
return 0;
}
Well the reason being, a variable gets garbage value( a value unknown/senseless to program) is when someone runs a program, it gets loaded in some part of RAM. Now it all depends what values were previously set to certain location, may be some other program was there previously.
It just happen the your program has loaded into a that location where it happens to be 0 value in RAM and that's what you are getting in return.
It quite possible that if restart your system and try running the same program then you might get garbage value.
Above statements are valid for variables which doesn't get initialized by the compiler.

Two different double values after adding a string variable

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.