简体   繁体   中英

I don't understand some parts of the code

I'm trying to understand a code from a programming site. This is not very well explained and I have not found the necessary answers.

So..What does it mean val[0] == '\\'' and x[0] == '\\"' ?

#include <iostream>

int main() {
    char a = '\'';
    std::string b = "\"";
    std::cout << "a=" << a << std::endl;
    std::cout << "b=" << b << std::endl;
    return 0;
}

The out put will be:

a='
b="

As the comments indicate this is the only way escape the ' and " characters. you can ignore [0] as that just indicates it's an array of chars and your accessing the first ones.

As other's have mentioned the backslash is used escape certain characters.

To illustrate why we need escape characters, look at the example below:

if(val[0] == ''' && x[0] == '"'){

}

To a person the intention is clear, but to a compiler this is ambiguous.

The compiler will first try to extract tokens from your program like so:

if => IF

( => (

val => IDENTIFIER

[ => [

0 => INTEGER

] => ]

== => EQ_OP

'' => CONSTANT

'&& x[0] == ' => CONSTANT

"'){} => Here it fails. Either the tokenizer sees the ", tries to match a string literal but the tokenizer prevents having an unescaped single quote in a string, and therefore doesn't match anything... causing an error. Option two, the tokenizer doesn't complain about the unescaped single quote, as " must having a closing ", and therefore does not find a match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM