6

I have seen this alternative to using CGRectMake() in order to initialise a CGRect variable:

CGRect frame = (CGRect){0,0,10,10};

My question is, how does CGRect frame = (CGRect){0,0,10,10}; work? What's going on behind the scenes? It looks like a c-style array is being initialised ({x,y,w,h}) which is then being cast as a CGRect struct - is this correct? If so, how is it possible to cast a c style array as a struct?

N.B. I am not asking if it is appropriate to use the above alternative to CGRectMake(), I only wish to understand why/how it works.

Barjavel
  • 1,626
  • 3
  • 19
  • 31
  • It simply works if the two statements create the same sequence of bytes. However, I am confused that you are using 0 and 10 instead of 0.0 and 10.0. 0 and 10 would be compiled as integer constants and 0.0 and 10.0 would be come out als float/double constants. Tehrefore I doubt that you could use float as a legal frame for anything useful. CGRect is a stucture made of CGPoint and CGSize. Both of them are made of two CGFload members (x and y in the case of CGPoint and width and height in the case of CGSize). – Hermann Klecker Aug 07 '12 at 08:54

3 Answers3

8

It's a so-called compound literal. You can read more about them in this article by Mike Ash: Friday Q&A 2011-02-18: Compound Literals.

omz
  • 53,243
  • 5
  • 129
  • 141
1

U can use like this:

CGRect rect = CGRectFromString(@"{{0, 0}, {612, 892}}"); // it contents { CGPoint origin;CGSize size;};
NSLog(@"rect : %@",NSStringFromCGRect(rect));
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
1

Check this:

CGPoint origin = {10, 20};
CGSize size = {100, 200};
CGRect rect = {origin, size};
ILYA2606
  • 587
  • 3
  • 7