If I switch on optimization in the IDE (Optimizations: Maximum Speed), the following (sample-)code gives unexpected results. But it seems to work fine without optimization (Optimizations: None). System: Windows 2000 (on AMD Athlon 64 Dual Core). Pelles C 5.00.
Input (say): test
Output: tst <--- ???
If I replace my_getchar() with getchar() in getword() no problem shows up.
#include <stdio.h>
#include <ctype.h>
void getword(char *);
int main(void)
{
char buffer[1000];
getword(buffer);
printf("%s\n", buffer);
return 0;
}
int my_getchar(void)
{
return getchar();
}
void getword(char *word)
{
char *w = word;
while (1)
{
*w = my_getchar();
if (*w == '\n') break;
w++;
}
*w = '\0';
return;
}
Yes, a bug: getchar() is normally a macro, and it contains a conditional operator ( ?: ) and a fetch with a post-increment (like *p++). If you put a conditional operator and a fetch with post-increment in a *return statement*, the fetch is acting like *++p, "thanks" to a new return optimization. Pity this wasn't found during beta testing; guess I should just skip that phase in the future...
Another way to "fix" this until I can upload a new version is just to undefine the getchar macro, somewhere after #include <stdio.h>:
like so:
#include <stdio.h>
#undef getchar
Never mind, Pelle. I'll "test" your compiler/IDE now by (extensively) using it. :)
Keep on the good work!
Thanks. I have this fixed now, and will upload it later - unless you find something else... ;)