question about gcc option..

H

herrcho

here is the code

#include <stdio.h>
int main()
{
char *str1="Borland International";
printf("%d\n", strlen(str1));
return 0;
}

i learned when i use strlen i have to include <string.h>
but the above runs o.k without <string.h>
i compiled it with gcc -Wall -ansi -pedantic -o

Could anyone explain about this ?
 
H

herrcho

Emmanuel said:
Missing


printf ("%d\n", (int) strlen(str1));

or better

printf ("%lu\n", (unsigned long) strlen(str1));


True enough.


What was the warning messages?


It runs by chance only. It's a UB, and UB are tricky. Don't do that.

there was no warning message..

by the way.. what is UB ?? i'm new to c programming..
 
E

Emmanuel Delahaye

herrcho said:
here is the code

#include <stdio.h>

Missing
#include said:
int main()
{
char *str1="Borland International";
printf("%d\n", strlen(str1));

printf ("%d\n", (int) strlen(str1));

or better

printf ("%lu\n", (unsigned long) strlen(str1));
return 0;
}

i learned when i use strlen i have to include <string.h>

True enough.
but the above runs o.k without <string.h>
i compiled it with gcc -Wall -ansi -pedantic -o

What was the warning messages?
Could anyone explain about this ?

It runs by chance only. It's a UB, and UB are tricky. Don't do that.
 
E

Emmanuel Delahaye

herrcho said:
there was no warning message..

Try again with

gcc -W -Wall -ansi -pedantic -o
by the way.. what is UB ?? i'm new to c programming..

Sorry about that. Undefined Behaviour. anything can happen, including 'good'
behaviour. This is why it's so a dangerous bug.
 
B

bd

here is the code

#include <stdio.h>
int main()
{
char *str1="Borland International";
printf("%d\n", strlen(str1));
return 0;
}

i learned when i use strlen i have to include <string.h> but the above
runs o.k without <string.h> i compiled it with gcc -Wall -ansi -pedantic
-o

Could anyone explain about this ?

If you don't #include it, it assumes it's a function that returns int, and
has whatever you gave it as arguments. strlen()'s prototype is:

size_t strlen(const char *)

Since size_t isn't the same as int, this is Undefined Behavior, so
anything can happen. In this case it apparently worked, but you shouldn't
rely on it.

Also, "%d" is incorrect - if you have a C99 compiler, you can use "%zu",
otherwise, cast to the proper type (for "%d", int)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,077
Messages
2,570,566
Members
47,202
Latest member
misc.

Latest Threads

Top