Question

I am currently learning and experimenting with C and am using Bloodshed's DEV-C++ as an IDE.

Now, I just realized that the following piece of code (as it is...no includes or nothing) compiles and runs :

main ()
{
    printf("%d", strlen("hello"));  
}

Now, if I'm not mistaken, shouldn't two header files be included in this source for it to work ? stdio.h and string.h...but as you can see, I did not add them and the code still compiled and ran successfully.

My complaint is that I want the compiler to be "strict" because since I'm still learning C, I don't want the code to run if normally it shouldn't.

So, is there any way to prevent Dev-C++ from 'correcting my mistakes' when it comes to includes, ie making it more kinda "strict" ?

Was it helpful?

Solution

C90 had a feature (absent of C99 and C++) called implicit function declaration: when you used a name not declared yet in a function call, the compiler behaved as if

extern int identifier();

had been seen. That feature has been dropped from C99 and most compilers had option to warn about this even before C99 was promulgated.

Even when staying in C90, it is not recommended style to use this. If you have to maintain code making use of this and can't add prototypes, check that:

  • the functions returns an int (it is the case for printf but the validity is implementation dependent for strlen which returns a size_t which can be int or something else)

  • the function isn't variadic (it is the case for strlen but not printf)

  • the type of the arguments is not modified by default argument promotions (char, short, float are) and you must pay attention to cast pointers to void* when needed when the expected type is void*, you have to pay attention to cast NULL to the correct pointer type. (These are the same things you have to pay attention for variadic arguments BTW).

If those conditions aren't met -- and they aren't for any calls in your code -- you enter in the realm of undefined behavior.

OTHER TIPS

I don't know if this actually is a DevC++ issue, but in any case you should consider ditching it. It is no longer being developed and is very buggy. I recommend changing to Code::Blocks, which is better in every way and alows you to use the very latest GCC compiler.

One of the possibilities for 'undefined behaviour' - which you get if you call a variadic function without a visible prototype - is that your code compiles and runs successfully.

If you're using gcc as the underlying compiler then you should be able to pass flags such as -std=c89 -pedantic -Wall -Wextra and get warnings about code such as the snippet that you've posted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top