C string and printf question
Ok in my book here it says doing the following would be bad
Code:
Code:
had the same result both ways and GCC gave no erros with -Wall of course this isent compleate code but its kinda a simple question. If the first code is incorrect can you give me a reason why it would be bad to do that as well. Sorry just trying to understand. |
Not quite certain what the author was getting at. Maybe it was because of the potential confusion between a character data type '%c' and the variable being a string. This could lead to confusion when revisiting the code.
What was the chapter of the book covering and was there anything else to explain why it was 'bad'? graeme. |
Don't believe everything you read...
If that's really what the author said, I'd consider getting a refund ;-)
|
Quote:
"%c" is a character where as you want a string of characters "%s". O no you dont lol. your just using one char, so i dont really know.;( |
Its a book by H.M. Deitel/P.J. Deitel C how to program second edition.
lol no refund needed book was only $4 its an older text book that i picked up somewhere in lack of being able to find anything else :p anway im in the section for Formated input/output and its one of the commen programming errors that they spek of Quote:
in looking at that maybe there talking about wierdness such as doing this. Code:
in that case i would see why it would be wrong but what i was doing earlier as being perfectly ok. |
Yes the way you coded it was correct. Omitting the element as in
Code:
printf("%c\n",test); graeme. |
i guess the second is recommended because its easier to debug a program.
and also for the sake of readability i guess. there r many other reasons but i think this is the most logical explaination |
The message about being wrong is a warning. That warning is based on human error.
Suppose you had a define MYTEST = "test string" and in the code you had char test[] = MYTEST; Your printf would work ok, as YOU know that MYTEST is long enough. But suppose, at 1am in the morning, in a rush to get a fix out, you had changed char test[] = "test"; Where would your expression point to? printf("%c\n",test[5]); To avoid errors, you can do what you want to do, but do lint your program before moving it to production. Lint is a wonderful detecter of pitfalls. |
All times are GMT -5. The time now is 01:02 PM. |