View previous topic :: View next topic |
Author |
Message |
soonc
Joined: 03 Dec 2013 Posts: 215
|
What's wrong with this sprintf() SOLVED |
Posted: Mon Jul 11, 2016 8:54 pm |
|
|
Compiler PCHWD V5.061
This line sprintf(temp_buf,"[Serial #: %s]", SerialNumber);
generates error
*** Error 7 .... Line 10243(52,53): Invalid Pre-Processor directive
Placed the ] a different place there is no error.
sprintf(temp_buf,"[Serial #: ]%s", SerialNumber);
I checked the help file and can't see anything about ] being used for the formatting.
Is this a compiler bug or some to do with sprintf() formatting ?
Digging a little deeper:
The error has nothing to do with sprintf() or [] ...
The compiler is reporting the wrong line number for a syntax error that has nothing to do with sprintf() !
It's interesting moving the ] to the left is %d and there is no error ! But the syntax ( a missing " ) four line above still compiles.
So the thing I learned is error reporting is far from perfect. |
|
|
gpsmikey
Joined: 16 Nov 2010 Posts: 588 Location: Kirkland, WA
|
|
Posted: Mon Jul 11, 2016 10:41 pm |
|
|
The C compiler only spits out an error when it figures out it is confused - that can often be one or more lines below where the actual error is.
mikey _________________ mikey
-- you can't have too many gadgets or too much disk space !
old engineering saying: 1+1 = 3 for sufficiently large values of 1 or small values of 3 |
|
|
jeremiah
Joined: 20 Jul 2010 Posts: 1349
|
Re: What's wrong with this sprintf() SOLVED |
Posted: Tue Jul 12, 2016 9:32 am |
|
|
soonc wrote: |
It's interesting moving the ] to the left is %d and there is no error ! But the syntax ( a missing " ) four line above still compiles.
So the thing I learned is error reporting is far from perfect. |
It actually makes a lot of sense. The error was on the correct line if you think about how parsing works.
If you have:
Code: |
sprintf(temp, "blah blah %x, var);
sprintf(temp2, "stuff is [cool");
|
then anything between two sets of quotes is considered a string
The compiler sees:
Code: |
sprintf(temp, "blah blah %x, var);\nsprintf(temp2, " stuff is [cool");
|
As your code. So everything between the first two quotes is considered a string and is a perfectly legal string. The stuff after the string looks like an error to the compiler. That's why things like missing quotes, semicolons, and braces can lead to really weird errors.
I really suggest if you ever have the time to try out:
http://compilers.iecc.com/crenshaw/
It gives a small sampling of how an old style compiler is written, but it can give real appreciation for understanding how compiler errors like this happen. Examples are very simple. |
|
|
|