Why doesn't the compiler report a missing semicolon?

后端 未结 5 1006
夕颜
夕颜 2020-12-13 16:55

I have this simple program:

#include 

struct S
{
    int i;
};

void swap(struct S *a, struct S *b)
{
    struct S temp;
    temp = *a    /*          


        
5条回答
  •  萌比男神i
    2020-12-13 17:09

    Why doesn't the compiler detect the missing semicolon?

    There are three things to remember.

    1. Line endings in C are just ordinary whitespace.
    2. * in C can be both a unary and a binary operator. As a unary operator it means "dereference", as a binary operator it means "multiply".
    3. The difference between unary and binary operators is determined from the context in which they are seen.

    The result of these two facts is when we parse.

     temp = *a    /* Oops, missing a semicolon here... */
     *a = *b;
    

    The first and last * are interpreted as unary but the second * is interpreted as binary. From a syntax perspective, this looks OK.

    It is only after parsing when the compiler tries to interpret the operators in the context of their operand types that an error is seen.

提交回复
热议问题