0
void addChar() {
    if (lexLen <= 98) {
        lexeme[lexLen++] = nextChar;
        lexeme[lexLen] = 0;
    } else {
        printf("Error - lexeme is too long \n");
    }
}

This is a snippet from a simple lexical analyzer... I'm not sure what the line lexeme[lexLen++] = nextChar; does. And in the next line, why does it assign 0 to lexLen.

It's original comment said its to add nextChar into lexeme, but I don't get how it does that.

1
  • lexLen++ is a postfix increment, so you are setting 0 on higher index in the lexeme array Commented Oct 11, 2020 at 23:24

3 Answers 3

1

lexeme is an array of char or a pointer to the first char in an array of char.

lexLen is the number of characters currently in the array, before a null character that marks the end of the string being built.

In lexeme[lexLen++] = nextChar;:

  • lexeme[lexLen] (ignore the ++ for the moment) is the element in the array that currently contains the null character marking the end.
  • lexeme[lexLen] = nextChar; changes that element to contain the value in nextChar. Thus, it puts this character from nextChar at the end of the string in the array.
  • The ++ increments lexLen after its value is used for the above.

lexeme[lexLen] = 0; puts a null character in the position after the end of the lengthened string, to mark its new end.

Sign up to request clarification or add additional context in comments.

Comments

0

Add nextChar after the original string, then add '\0' at the end, this is a C style string.

At the same time, if the length of string more than 98, print error message

Comments

0

Lexeme is an array of characters. Gven the range checks I am going to assume it's 100 characters long and it's already had memory allocated. Your code does not show that.

lexLen is a number. It would appear to be pointing at the end of your string. So if Lexeme currently contains "hello", lexLen will be 5.

lexeme[lexLen++] = nextChar; 

This line does two things. It says "the character at position 5 in lexeme should be set to nextchar. It also increments lexLen (++), so lexLen is now 6.

lexeme[lexLen] = 0;

This says "the character at position 6 in lexeme should be set to 0". This is because strings in C should be null terminated. (0 == null). The null marks the end of the string. The next time AddChar() is called it will be overwritten.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.