Tuesday, July 26, 2005

addresses and etc

/*addresses of static, struct, temporary variables etc */

#include <stdio.h>

#define PRINT(msg, ptr) printf("%s: \t%p\n", msg, (void*)(ptr))

struct s { int a[1]; };

struct s sfunc()
  {
  struct s s = {0};
  PRINT("inside fn", s.a);     /* address of internal variable */
  return s;
  }

static struct s sfunc_static_obj = {0};

/* sfunc_static() is declared inline so that there is no need
   to return through a temporary */
inline static
struct s sfunc_static()
  {
  PRINT("inside fn", sfunc_static_obj.a); /* address of the static object */
  return sfunc_static_obj;
  }

inline static
struct s sfunc_ptrarg(struct s *ps)
  {
  PRINT("inside fn", (*ps).a);
  return *ps;
  }

int main()
  {
  struct s s1 = {0}, s2 = {0};
  const struct s sc = {0};

  puts("\n*&:");
  PRINT("s1", &s1);
  PRINT("*&s1", (*&s1).a);  /* control code, expected equal */

  puts("\nfunction call:");
  PRINT("fn return", sfunc().a);   /* address of the temporary */

  puts("\nfunction call (static object):");
  PRINT("fn return", sfunc_static().a);   /* address of the temporary */

  puts("\nfunction call (through argument):");
  PRINT("s1", s1.a);
  PRINT("fn return", sfunc_ptrarg(&s1).a);   /* address of the temporary */

  puts("\nassignment operator:");
  PRINT("s1", s1.a);
  PRINT("s2", s2.a);
  PRINT("val", (s1 = s2).a);   /* address of the temporary */

  puts("\nconditional operator:");
  PRINT("s1", s1.a);
  PRINT("?:", (1?s1:s2).a);

  puts("\ncomma operator:");
  PRINT("s1", s1.a);
  PRINT("(,)", (0,s1).a);

puts("\ncomma operator, const object:");
  PRINT("sc", sc.a);
  PRINT("(,)", (0,sc).a);
  return 0;
  }

 

Pradyut
http://pradyut.tk
http://groups.yahoo.com/group/d_dom/
http://groups-beta.google.com/group/oop_programming
India

 

No comments: