Search code examples
arithmetic-expressionsprocessing-efficiency

Extra computation steps on adding brackets?


Ok, so just a question popped up in my mind while writing some code. Does the CPU compute this

gap = (gap*3) + 1;

with the same efficiency as the below expression without the brackets?

gap = gap*3 + 1;

Update to be more clarifying:

Often while writing arithmetic expressions, we tend to add brackets to make the code easier to read, even if the brackets do not change what the expression evaluates to. So the question is, does adding such brackets have any affect on the performance?


Solution

  • As mentioned above in the comments:

    file test1.c:

    int main(void)
    {
        int gap = 1;
        gap = (gap*3) + 1;
        return gap;
    }
    

    file test2.c:

    int main(void)
    {
        int gap = 1;
        gap = gap*3 + 1;
        return gap;
    }
    

    Using gcc and its -S option ("Compile only; do not assemble or link"): gcc -S test1.c && gcc -S test2.c. Comparing those two files:

    $ diff test1.s test2.s
    1c1
    <   .file   "test1.c"
    ---
    >   .file   "test2.c"
    

    (i.e. only the file names differ in the first line)

    When you still don't believe me (for this particular example), then you can further compile & assemble: gcc test1.c -o test1 && gcc test2.c -o test2. Comparing those binary files (or rather ELF executables) will give you one byte difference, i.e. the file name again:

    $ hexdump -C test1 > hex1.txt && hexdump -C test2 > hex2.txt
    $ diff hex1.txt hex2.txt 
    387c387
    < 00001fc0  79 5f 65 6e 74 72 79 00  74 65 73 74 31 2e 63 00  |y_entry.test1.c.|
    ---
    > 00001fc0  79 5f 65 6e 74 72 79 00  74 65 73 74 32 2e 63 00  |y_entry.test2.c.|