Re: Referencing struct fields in C
Re: Referencing struct fields in C
- Subject: Re: Referencing struct fields in C
- From: Oleg Krupnov <email@hidden>
- Date: Mon, 30 May 2011 15:20:47 +0300
And no, I cannot move the for loop inside the if, because the
(omitted) code inside the for loop is huge, and I would hate to
duplicate it in the both if clauses...
Thanks Dmitry!
On Mon, May 30, 2011 at 3:12 PM, Dmitry Muraviev <email@hidden> wrote:
> А почему вы не хотите перенести цикл внутрь условия?
>
>
>
> On 2011/May/30, at 16:02:09, Oleg Krupnov wrote:
>
>> This question is related to C language, rather than Obj-C.
>>
>> I have a data structure
>>
>> typedef struct
>> {
>> int x;
>> int y;
>> } A;
>>
>> In my code, I have a function foo(bool xOrY) that runs a long-lasting
>> loop that iterates through a huge array of A structures and for each
>> structure, it should get x or y field. The choice of x or y is the
>> same on each iteration, but may change between different calls of
>> foo(bool xOrY).
>>
>> void foo(bool xOrY)
>> {
>> for(int i = 0; i < count; ++i)
>> {
>> if (xOrY)
>> {
>> int value = a[i].y;
>> ...
>> }
>> else
>> {
>> int value = a[i].x;
>> ...
>> }
>> }
>> }
>>
>> I am looking to optimize this code, because the line if(xOrY) yields
>> the same result on each step. So I am thinking about this code:
>>
>>
>> void foo(bool xOrY)
>> {
>> struct A test;
>> size_t offset = 0;
>> if (xOrY)
>> {
>> offset = (char*)&(a.y) - (char*)&a;
>> }
>> else
>> {
>> offset = (char*)&(a.x) - (char*)&a;
>> }
>>
>> for(int i = 0; i < count; ++i)
>> {
>> int value = *(int*)((char*)a + offset);
>> }
>> }
>>
>>
>> Is this approach valid at all? The compiler doesn't show any problem,
>> but I wonder if there can be any caveats related to structure aligning
>> etc.? It seems like it should not be a problem, because I am measuring
>> the offset in run time, but I am not quite sure...
>>
>> I also thought about using a function pointer to switch between two
>> tiny functions, one of them returning x and the other y from a given
>> struct instance, but it seems somewhat more expensive than the above
>> approach (push/pop param from stack, call, return)
>>
>> Thanks a lot!
>> _______________________________________________
>>
>> Cocoa-dev mailing list (email@hidden)
>>
>> Please do not post admin requests or moderator comments to the list.
>> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>>
>> Help/Unsubscribe/Update your Subscription:
>>
>> This email sent to email@hidden
>
> Best regards,
>
> Dmitry Muraviev
> Software Engineer
> Vidau Systems
>
>
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden