Know your language – Part 1

1. sizeof operator (c/c++)
We know that the sizeof(variable) returns the size of the variable and sizeof(pointer) returns the amount of memory that can be addressed  in bytes.

#include
#include
using namespace std;
void sz(int p[]){
   cout<<"sz: "<<sizeof(p)<<"\n";
}
int main(){
   int p[]={1,2,3,4};
   cout<<"main: "<<sizeof(p)<<"\n";
   sz(p);
   cout<<"main: "<<sizeof(p)<<"\n";
   cout<<"sizeof(p):"<<sizeof(p)<<"   sizeof(&p[0]):"<<sizeof(&p[0])<<"\n";
   return 0;
}

output:

main: 16
sz: 8
main: 16
sizeof(p):16   sizeof(&p[0]):8

int p[4];
we know that p points to the first element in the array so the sizeof(p) should return the size of the memory being addressed, and so p is same as &p[0] and so sizeof(p) and sizeof(&p[0]) should be same.But that is not the case, sizeof(p) gives the sizeof the array in bytes i.e sizeof(int)*4 in this case.
to learn more go here: http://www.cplusplus.com/faq/sequences/arrays/sizeof-array/

2. Sequence points
A sequence point is a point in the programs execution where all previous side effects shall have taken place and where all subsequent side effects shall not have taken place.
So you should update a variable only once between sequence points.
examples of codes that have undefined behaviour.


int x=5,y=0,z;
x=x++; // undefined behavior
z=y++ + ++ y;// undefined behavior

3. Changing the value of  a constant variable(only c)

const int f=2;
f=8; //error: assignment of read-only variable ‘f’
//but u can use pointers to change its value and this only works in c
//gives warnings(warning: assignment discards ‘const’ qualifier from pointer target type) but works
int *p;
 p=&f;
*p=8;
printf("%d\n",f); //prints 8

4. Structure padding

#include<stdio.h>
struct basic{
   int a;  char b;
};
struct kaboom{
   int a;  char c;  int b;  char d;
};
struct noKaboom{
   int a;  char c;  char d;  int b;
};
struct f{
  int a; char c[4]; int d;
};
int main(){
   printf("%zu\n",sizeof(struct basic));
   printf("%zu %zu\n",sizeof(struct kaboom),sizeof(struct noKaboom));
   printf("%zu\n",sizeof(struct f));
   return 0;
}

the sizeof struct basic is not sizeof(int)+ sizeof(char)
when the size goes over a word length (specific to each computer) the rest is padded to make it a multiple of 1 word length
in this case the word length is 4 (on a 32 bit machine) so size of int+char is 5 so it makes it 8 by padding it.

why is this done?
It is expensive to work on subword size data types so compiler will pad them so that they are on the word boundary.
Why is it expensive?
It is because the instruction set of most processors is optimized to move 1 word data between the processor and the memory.

you can read more about it here: http://en.wikipedia.org/wiki/Data_structure_alignment

the output of the above program is:

8
16 12
12

5. Wtf is happening here!? 

–>>http://ioccc.org/2000/dhyang.c<<–
jackie chan wtf

😛