Backslash in c source file

2019-07-12 15:59发布

问题:

I have follow code same as it is on different lines:

frame_rate = (float)
                ( ( ( frames * media_timescale) + \   //WHY???
                    ( media_duration >> 1 ) ) /
                 media_duration);

I am not understanding what is backslash doing in source file ? Also to calculate the frame rate simply we can do as follow:

frame_rate = (float) ( (  frames * media_timescale) / media_duration);

Is there any specific intention to write first type of code?

回答1:

It's a line-continuation escape. It means the compiler will consider the next line as a part of the current line.

It makes the code you show in practice being

frame_rate = (float)
                ( ( ( frames * media_timescale) + ( media_duration >> 1 ) ) /
                 media_duration);

There's no real need for it in this case though, except as maybe some style-guide followed by the author had it as a requirement.

Line continuation is needed to define "multi-line" macros, and are also often used for long strings. But besides those places, it serves no real purpose.



回答2:

Backslash is used to split a long line into 2 shorter lines, without signifying an end of the statement. This is usually done when a single line statement might be too long to read.



回答3:

The backslash is a line continuation. It makes no difference other than for readability purposes (80 characters per line is usually the recommended limit for most style guides).

See: How can I do a line break (line continuation) in Python?



回答4:

I don't think anybody could describe this better than the standard. Hence, according to C11/section 5.1.1.2p1, which summarises the stages of translation (compilation, if you will) which occur when you invoke your compiler:

  1. Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place.

Thus, from your example, the first line ends up effectively spliced (joined) with the second due to the combination of the backslash and newline.



标签: c video hevc