This question already has answers here:
Accessing inactive union member and undefined behavior?
(5 answers)
Closed 6 years ago.
Declaring variable without initializing it will have a garbage value so in this program I am using a union:
union un
{
int value;
char c;
};
int main()
{
un x;
x.c = 'A';
cout << x.value << endl; // garbage: ok
}
above it is ok when printing value it produces a garbage value as long as we didn't initialize it.
but look at this program:
union un
{
int value;
char c;
}r;
int main()
{
r.c = 'A';
cout << r.value << endl; // 65! as we know the ASCII value of character 'A' is 65
}
so what is the difference between the two program above and why in the second one value gets the value of c?
Your r is a global variable. And these are initialized to zero. The first byte of value is c, the other bytes are zeros.
In contrast, x is a local variable, and those aren't initialied. The first byte of value is c too, but other bytes are like random or garbage, as you call it.
Related
This question already has answers here:
C++ Returning Array, data loss [duplicate]
(1 answer)
error: function returns address of local variable
(8 answers)
Closed 2 years ago.
Please find the code snippet shown below:
unsigned char au8Buffer[4] = {1, 2 , 3, 4} ;//Global array declared
class abc
{
public:
unsigned char *Getheader();
}
void func(abc *ptr)
{
unsigned int a, b;
a = (ptr->Getheader())[0];
b = (ptr->Getheader())[1];
printf("the value of A = %d\n",a);
printf("the value of B = %d\n",b);
}
unsigned char * abc:: Getheader(void)
{
static int count = 0;
count++;
if(1 == count)
return &au8Buffer[0];
else
return &au8Buffer[1];
}
main()
{
abc Testobj;
func(&Testobj);
}
Can someone please tell me why is the value of the variable 'b' coming as 3?. I was expecting the value of b to be 2.
Every object and reference has a lifetime, which is a runtime property: for any object or reference, there is a point of execution of a program when its lifetime begins, and there is a moment when it ends.
The lifetime of au8Buffer ends when the function ends. Returning a pointer to its contents results in undefined values.
You can create a constructor for abc and move the initialization of au8Buffer into the constructor.
This question already has answers here:
Accessing inactive union member and undefined behavior?
(5 answers)
Closed 2 years ago.
For the following code
#include <iostream>
using namespace std;
union type
{
int a;
char b ;
};
int main()
{
type first;
first.b = 'a';
cout << first.a << " " << first.b << endl;
}
the output is -858993567 a (MSVC) or 4201057 a(g++ MINGW).
but for
#include <iostream>
using namespace std;
union type
{
int a;
char b ;
};
int main()
{
type first;
first.a = 0;
first.b = 'a';
cout << first.a << " " << first.b << endl;
}
the output is 97 a
And these values are fixed under every circumstances (tried rebooting and creating new workspace/file, hence not garbage values).
So, why did the initialization (in the second case) made a difference?
I have tried it both on visual studio (using MSVC) and visual studio code (using g++).
Update 1
I checked on online IDE which probably use Linux g++, and they give the exact expected answer i.e., 97 a, in both the cases.
If you specify first.a in first code sample - you will get fixed, stable value.
You have union with 4 bytes size and initialize only one byte of them.
Union is like type who can holds any type but this types musts be writed in definition of union, like this:
union Example {
char a;
std::int32_t b;
};
Example ex; /// Create object of union
ex.a = 'c'; /// At this moment a member is valid and b is invalid
std::cout << ex.b; /// This cause undefined behavior
Be aware, size of union object is size of type who need most bytes. In this case size is same as size of b property.
This question already has answers here:
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 3 years ago.
I'm trying to learn C++, specifically how to declare and initialize variables. I wrote this code, and I don't know why the variable c is giving a value that I have not assigned it yet.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!\n";
int a, b;
a = 1;
b = 2;
int d(4);
int result;
auto num = b;
decltype(b) c;
result = a + b - d;
cout << c;
}
The output is -2, but I didn't state c = -2 anywhere!
If you have not initialized the variable, it contains garbage value.
In C/C++, the values declared within a function represent some bytes of main memory on the cpu stack. Those bytes are usually dirty and need initialization. If you don't the values are undefined. That you're always getting '-2' is merely coincidence.
This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 6 years ago.
I have these two almost identical bits of c++
#include <iostream>
using namespace std;
int main(){
int a = 0;
int b = 1;
int c = 2;
int d = 3;
int *p = &a;
cout << &c << endl;
cout << *(p+1);
}
with the output:
0x7ffd7b16998c
2
and
#include <iostream>
using namespace std;
int main(){
int a = 0;
int b = 1;
int c = 2;
int d = 3;
int *p = &a;
cout << &d << endl;
cout << *(p+1);
}
which produces the output:
0x7ffdb7ea105c
3
Why does the value of *(p+1) depend on what I output beforehand?
If I delete the line
cout << &c << endl;
completely i get the expected 1 as an output.
What on earth is happening?
What's happening is undefined behavior.
When you obtain a pointer to an int, you are allowed to use the value of that pointer alone; pointer arithmetic is meaningless.
In order for p+1 to produce an address that you can dereference, p must point to an array element other than its last element. In all other situations, reading *(p+1) is undefined.
Standards aside, the CPU must be taking that value from some place. You assume that the place must be the address of b, which is declared immediately after a. However, C++ makes no guarantees about location of local variables in memory relative to each other. It appears that the compiler reorders your variables, producing an output that you did not expect (and it's undefined anyway).
*(p+1) accesses memory after a so it's Undefined Behaviour.
Propably you intended (*p)+1 to increase a by 1?
This question already has answers here:
Why are references not reseatable in C++
(17 answers)
Closed 7 years ago.
According to these links: stackoverflow question and C++ FQA references cannot refer to another object/ variable well once they're initialized, but what about the below code?
// Example program in C++
#include <iostream>
using namespace std;
int main()
{
int x=10, z=12;
int &y=x;
++y;
y=z; //valid?
cout << x << ", "<< y <<", " << z << endl; // prints 12, 12, 12
return 0;
}
Below is the C code regarding pointer reseating and it seems valid, am I right?
#include <stdio.h>
int main(int argc, char *argv[])
{
int a=10, b=20;
int *ptr;
ptr = &a;
ptr = &b;
printf("%d\n",a); // prints 10
printf("%d\n",*ptr); // prints 20
return 0;
}
Can someone clear the above concept in the above two codes?
y=z; //valid?
Absolutely! However, it does not mean "y refers to z from now on". It means "set the value of z to whatever y is currently referring", which is x. Hence, y=z is another way of writing x=z.
Below is the C code regarding pointer reseating and it seems valid, am I right?
Unlike references, pointers can be re-pointed, so the re-assignment of the pointer makes it point to a different variable. Your program does not illustrate this, however, because two assignments to ptr happen without any reads of ptr in between, so only the second assignment stays.
In y=z
Its not refering to another variable its just assigning the value of z to y which is 12 and since y is reference to x, x also gets assigned value 12.
so x=y=z=12
But in pointers its valid to change the address it points to:
ptr = &a;
ptr = &b; //valid