bingoohuang / blog

write blogs with issues
MIT License
178 stars 24 forks source link

一些有趣的代码片段 #180

Open bingoohuang opened 4 years ago

bingoohuang commented 4 years ago

C 代码里面的网址

C 代码里面加一行,直接写一个网址,并不会报错,代码还是能够运行。这篇文章解释了为什么。

Here is an interesting C puzzle I created recently. It is a silly one but you might find it amusing.

#include <stdio.h>

int main()
{
    https://susam.in/
    printf("hello, world\n");
    return 0;
}

This code compiles and runs successfully.

$ c99 hello.c && ./a.out
hello, world

在线跑跑看

However, the C99 standard does not mention anywhere that a URL is a valid syntactic element in C. How does this code work then?

Update on 04 Jun 2011: The puzzle has been solved in the comments section. If you want to think about the problem before you see the solutions, this is a good time to pause and think about it. There are spoilers ahead.

The code works fine because https: is a label and // following it begins a comment. In case, you are wondering if // is indeed a valid comment in C, yes, it is, since C99. Download the C99 standard, go to section 6.4.9 (Comments) and read the second point which mentions this:

Except within a character constant, a string literal, or a comment, the characters // introduce a comment that includes all multibyte characters up to, but not including, the next new-line character. The contents of such a comment are examined only to identify multibyte characters and to find the terminating new-line character.