Reputation: 7864
I'm compiling the below C code with gcc
. No errors are thrown during compilation or at runtime. I ran through the code with gdb
, and the answer given in sum
is correct at the end, yet the printf()
does not display anything on the screen. I've tried all sorts of combinations of fprintf()
, printf()
, and fflush()
, but nothing works.
What do I need to change so the program will print the result to stdout
?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 9;
int i, sum; i = 1, sum = 0;
while (i < 2 * num) {
sum = sum + i * i;
++i;
}
printf("sum: %d\n", sum);
fflush(stdout);
return 0;
}
Upvotes: 1
Views: 2231
Reputation: 5721
There is nothing wrong with your program. It has to work. Try running it with redirection:
./a.out > myout
..and see if you get any output. If not, I'd suspect there is a problem with some kind of standard library mismatch.
Another option to check would be to build using SUN C compiler as opposed to gcc and see if that works. If it does, gcc is the culprit.
Upvotes: 0
Reputation: 263617
The code is correct, and should print sum: 1785
for any conforming implementation.
This is a guess (update: which turns out to be correct), but ...
You've named the source file test.c
, and you compile it with:
$ gcc test.c -o test
(or something similar) and execute it with:
$ test
which produces no output.
The problem is that test
is a standard Unix command (and also a built-in command in some shells). When you type a command name to the shell, it first looks for built-in commands, then for executables in directories specified in your $PATH
environment variable.
To execute a command in the current directory, prepend ./
to the name:
$ ./test
sum: 1785
$
This applies to any command in the current directory. There are so many built-in commands that you can't reasonably avoid colliding with them. Cultivating the habit of running executables in the current directory by typing ./whatever
means that name collisions don't matter.
(Don't be tempted to add .
to the front of your $PATH
; that's dangerous. Think about what could happen if you cd
into a directory and type ls
, if there happens to be a malicious ls
command there.)
Upvotes: 10