Path: csiph.com!news.mixmin.net!border2.nntp.ams1.giganews.com!nntp.giganews.com!buffer2.nntp.ams1.giganews.com!nntp.brightview.co.uk!news.brightview.co.uk.POSTED!not-for-mail NNTP-Posting-Date: Thu, 08 Jun 2017 02:16:21 -0500 From: Gareth Owen Newsgroups: comp.lang.c Subject: Re: memscan() function or equivalent References: <20170607154705.f161b2807eb2b1a8dc12d389@gmail.com> <12fb0e96-0ac3-442d-8d04-baaef4234a85@googlegroups.com> <20170607164800.a6fba9d07170ec5d056d25a0@gmail.com> <878tl3g5jw.fsf@bsb.me.uk> <87wp8n4lqm.fsf@gmail.com> Date: Thu, 08 Jun 2017 08:16:20 +0100 Message-ID: <87zidj9cfv.fsf@gmail.com> User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux) Cancel-Lock: sha1:ZWH33WsJMcOBVVCzWOY86Z0XxzY= MIME-Version: 1.0 Content-Type: text/plain Lines: 34 X-Usenet-Provider: http://www.giganews.com X-Trace: sv3-wwH7LeoywdtUl0nZB/WbrmndyCXdxXjGG+pS+Vmw0XqpZyxvydScqtu9RHcyWTFlP7l2tLoOWxKD3W7!657RlgOlfui9GlS3EaT4tkVeZB8pjRUQEhhPzNNw4SOGoPLoodhSoVfN8vZTqFDqhWLo3us= X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.40 X-Original-Bytes: 2416 Xref: csiph.com comp.lang.c:111798 David Brown writes: > In some cases, a conditional branch would be more efficient, in other > cases an integer selection instruction or some other way of producing > a 0 or 1, followed by an unconditional add, would be best. A compiler > /could/ choose the method it thought was most efficient, but it could > also reasonably choose the method that matched the source code best, > on the assumption that the programmer knows best. I agree with all of this. With optimisation off ("a supercat compiler") I would expect different code generated - code that logically mapped to the syntax. With optimisation maxed out, I would hope the compiler compiled them the same. Did a quick test gcc -O0 and -O3 produce the subtly different code for both of these functions (this is gcc-6.2 on ubuntu), but my assembler-fu isn't enough to tell which is more efficient. #include int count(const char * b,char c,size_t n) { int ct = 0; for(size_t idx = 0; idx < n; ++idx) ct += (*b == c); return ct; } int count2(const char * b,char c,size_t n) { int ct = 0; for(size_t idx = 0; idx < n; ++idx) if(*b == c) ++ct; return ct; }