I am very new to C Programming and have a doubt… I’ve been asked to find errors in certain segments of C code… and this segment has me a bit confused so would appreciate the help…
int main(void)
{
int myInt = 5;
printf("myInt = %d");
return 0;
}
As far as i understand there is nothing wrong in this code. What i wanna know is why is this statement printing out a random number ??
The output i get is
myInt = 1252057154
Would appreciate the help… Thanks
You should read more about C programming.
And you should enable all warnings and debugging when compiling. With GCC, this means
gcc -Wall -Wextra -g(on Linux at least).When compiling with
I am getting the following warnings:
So the correction is simple:
which gets compiled without warnings.
Notice the
\nat the end ofprintfformat string. It is important.Always enable all the warnings the compiler can give you and trust the compiler, so correct your code till no warnings is given.
And learn to use the debugger (e.g.
gdbon Linux).The behavior you observed is undefined behavior; anything could happen with a standard conforming implementation of C (even an explosion).
Happy hacking.