Promotional Hierarchy of Fundamental data types
long Double HighestDouble
float
unsigned long int unsigned long
long int or long
unsigned int
int
unsigned short int or unsigned short
short or short int
unsigned char
char
bool Lowest
Conversion from highest type to lowest type will result in loss of data.
//sizeofstructunion.C
int main()
{
struct {
char a[20];
int n;
union{
double b;
struct {
char d[15];
float e;
}x;
}y;
}z;
cout << "z.y.x size: " << sizeof(z.y.x) << endl;
cout << "z.y size: " << sizeof(z.y) << endl;
cout << "z size: " << sizeof(z) << endl;
return 0;
}
result:
z.y.x size: 20 // char array size is 15, float size 4, consider alignment(padding). multiply the size of float to equalize or exceed array size of 15. i.e 4*4=16 (here we got one more than 15). Hence size of struct is 16 of array and 4 of float. 4+16= 20.
z.y size: 24 // size of struct member (20 bytes)in union is more than double . double b size is 8 bytes. Consider alignment(padding). Multiply the size of double to equalize or exceed the size of struct. Hence we get 8*3= 24.
z size: 48 // sizeof union + char a + int n -> 24+ 20+4 = 48.
using namespace std;
struct test {
static int a;
int b;
int c;
}obj;
int test::a=10;
int main()
{
cout << "test" << endl;
cout << "now a:" << obj.a << endl;
cout << "now b:" << obj.b << endl;
cout << "now c:" << obj.c;
return 0;
}
//structdeclaration.C
#include<iostream>using namespace std;
struct test {
static int a;
int b;
int c;
}obj;
int test::a=10;
int main()
{
cout << "test" << endl;
cout << "now a:" << obj.a << endl;
cout << "now b:" << obj.b << endl;
cout << "now c:" << obj.c;
return 0;
}
//declare a variable
extern int val; //declaration of a variable
int iglobal; // declaration as well as definition, coz global variables intialized to zero
int localVariable; // declaration as well as definition coz local variable are having garbage values.
in C programming/ C++ programming, global structure members are initialized to zero.
local structure in C/C++ structure members will have garbage value.
No comments:
Post a Comment