Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comment wizardry

I am not a level 60 wizard yet, so I've got a question based on the following sentence in the Wikipedia article on magic:

Any comment that has an effect on the code is magic.

How is that? In what languages is such a thing possible? More specifically, what effect can a comment have on the code?

like image 381
Shahbaz Avatar asked Dec 02 '25 09:12

Shahbaz


2 Answers

Magic comments take various forms. In Ruby, a comment can be placed at the top of the file, which specifies an encoding that the interpreter will use when reading in the file:

# -*- coding: UTF-8 -*-

more


In Unix systems, the first line can be a shebang. In any language with octothorpes for comments, this ammounts to a comment that the OS reads to decide how to interpret the file

#!/bin/bash
echo hello from bash

more


In Haskell, certain types of comments known as pragmas can be used to switch on (or off) language features.

{-# LANGUAGE OverlappingInstances, NoTypeFamilies #-}

more

like image 81
Joshua Cheek Avatar answered Dec 06 '25 08:12

Joshua Cheek


I wouldn't worry too much about that remark in Wikipedia. I think the intention is just to say that a comment "should not" affect behavior (since that's what comment means), so if it does then it must be some kind of special case and hence is "magic" by the definition in use in that section of the article. The author of that line of the article didn't necessarily have any particular language in mind.

If you fancy being pedantic, then a comment can easily affect program behavior in C (in this example by containing a number of line breaks):

#include <stdio.h>

int main() {
    /* If this multi-line comment were deleted, then
       the line-numbers in the remainder of the file
       would be smaller. Boring magic.
    */
    printf("%d\n", __LINE__);
}

I'm pretty sure that this is not what the author of the remark intended, so the remark isn't precise. It's special cases of the comment syntax that are "magic".

like image 39
Steve Jessop Avatar answered Dec 06 '25 06:12

Steve Jessop