HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Why doesn't the C/C++ compilers create different tokens for different types of numbers?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
whythecompilerscreatenumbersdifferentdoesnfortypestokens

Problem

Based on GeeksforGeeks and many other sites, the C/C++ compilers will create the same token for float/int etc.

However if we have something like this:

int A[10.5];


then will there be a parser error or semantic error?

The book that I'm reading says the parser rather than the semantic routines will detect it, but after the lexical analysis wouldn't that be converted to this:

A[Constants];


meaning the 10.5 will be converted to a Constants token based on that website? Therefore the parser will not notice this is an error because both of 10 and 10.5 will be Constants!

So which one is right? Will the parser or one of the semantic routines detects this error? Do the C/C++ compilers create the same tokens for int numbers and floats?

Solution

This is in fact an implementation detail of the compiler. The page you referenced only shows one way of assigning types to tokens, while there are also others. The compiler could have a lexer that distinguishes between integral and non-integral constants and the parser then cannot match the declaration

int A[10.5];


to any rule. But giving an error message stating exactly this to the programmer is not very helpful. Modern C++ compilers have quite complex parsing and compiling routines that give more information in case of errors. As an example, GCC will yield:

me@my-computer:/tmp$ g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:9:15: error: size of array ‘A’ has non-integral type ‘double’
     int A[10.5];
           ^


So you will get quite a good error message, and for obtaining it, some semantic interpretation was actually performed.

Code Snippets

int A[10.5];
me@my-computer:/tmp$ g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:9:15: error: size of array ‘A’ has non-integral type ‘double’
     int A[10.5];
           ^

Context

StackExchange Computer Science Q#89856, answer score: 4

Revisions (0)

No revisions yet.