"DeltaOne" <sh**********@wipro.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
#include<stdio.h>
typedef struct test{
int i;
int j;
}test;
main(){
test var;
var.i=10;
var.j=20;
printf("i==%d i==%d \n",var,var.i);
return 1;
}
Compiler in VC++ and see that you get the output is i==10 i==20
Can any one explain Why this thing happens?even though i give the
address of var.i why the value of j is geting printed?
Thats undefined behaviour in C++ since its not the address of &var.i that is
passed (only the type). Printf is being told to extract an integer at &var
and then another integer from the same object with complete disregard for
access specifiers.
use std::cout instead. Note that you can't output var unless you provide
operator<<(...). Thats by design.
#include<iostream>
struct Test
{
int i;
int j;
};
int main()
{
Test var;
var.i=10;
var.j=20;
// std::cout << "var = " << var; // no operator defined...
std::cout << "i = " << var.i;
std::cout << "\nj = " << var.j;
return 0;
}
result:
i = 10
j = 20
If you still need to be convinced of printf's deficiencies, consider:
#include<stdio.h>
struct Test
{
Test(int ii, int jj) : i(ii), j(jj) { }
private:
int i;
int j;
};
main()
{
Test var(10, 20);
printf("i==%d i==%d \n",var,var);
return 0;
}
result:
i==10 i==20
Again: undefined behaviour and just wrong.