For loop with pointer in C

49,445

Solution 1

In a Boolean context such as the condition of a for loop, each expression in C evaluates to true (non-zero) or false (zero).

You want the for loop to terminate, when it reaches the end of the string.

In C, each string is terminated with the character '\0', which is practically 0. So, when the for loop reaches the end of string, *p evaluates to '\0', which is 0, which evaluates to false, which terminates the for loop.

Solution 2

The for loop will terminate if whatever lies between the two ; in the statement is zero (false). *p dereferences p and returns the char, p points to. According to Dennis Ritchie "C treats strings as arrays of characters conventionally terminated by a marker". That marker is the null character with (ASCII) value of zero. So, this for loop :

for (p = str; *p; p++)

is equivalent to these

for (p = str; *p != '\0'; p++)
for (p = str; *p != 0; p++)
for (p = str; p[0] != '\0'; p++)

Another name for the null terminating character is sentinel or according to Donald Knuth "dummy value" (Art of Computer Programming, Volume 1). Here is a diagram of the str string, the indexes (offsets from the start) of each character and the values at each index :

enter image description here

For completeness and after a request at the comments here is what the debugger sees in the memory block that str occupies :

0x00007fffffffe6a0:
  0x53 0x6f 0x6d 0x65 0x20 0x54 0x65 0x78 0x74 0x00 0x00 0x00 0x00 0x00 0x00 0x00
     S    o    m    e         T    e    x    t
  1. The hex value at the first line is the address (64bit) of this memory block. That's where p points to at the start of the for loop.
  2. On the 2nd line you see the hex values of the letters in your string. You can see an ASCII table here. The last char in your string is t with hex value of 0x74. After that you have the string's null character 0x00. Then you see a few more null characters because I built in debug mode and the compiler zero-initialized. Normally you would see garbage (seemingly random values)
  3. On the 3rd line I added the chars of your string for reference

I understand you are on precipitous learning curve at the moment with pointers in C, but eventually you'll be able to say "I C the point"

Solution 3

Before diving in, I would like to state a simple rule in C regarding an expression

When C requires the Boolean value of an expression, a false value is inferred when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes

if(expr)

where expr is any expression at all, the compiler essentially acts as if it had been written as

if((expr) != 0)  

Now coming to your question:

What does the *p do in the following loop?

In C, strings are terminated by a null character '\0'.

enter image description here

Every character has a decimal equivalent. This '\0' is an ASCII escape character. The decimal equivalent of '\0' is 0.

So, the expression *p in loop just check that the decimal equivalent of character at the memory address pointed by p is either a zero or non-zero. When p reaches the end of the string and finds the first '\0' character, the expression *p returns1 a zero value. A zero means false in C. This is equivalent to testing *p != '\0' or *p != 0 as stated above.

This is how it works:

enter image description here


1 When *p evaluates then the value of *p is fetched from memory. This value is the value of expression *p.

Solution 4

This could be rewritten like this

for (p = str; *p != '\0'; p++)
{
    // Code
}

In C, a string must always be terminated by a null character, which is the same as '\0' or 0.

Solution 5

Lets analyze it the dry but depth way!

Or as D. Ritchie would say: Let's do it with the power of assembly language and the convenience of … assembly language.


I'll try to explain all necessary aspects by referencing the ISO/IEC:9899 (emphasis mine)- C99 standard. (The post style is motivated by Donald Knuth's phrase "Science is what we understand well enough to explain to a computer. Art is everything else we do. ")

First of all, lets inspect what exactly is the for-loop supposed to do!

Referring to ISO/IEC:9899 6.8.5 "Iteration statements"

Semantics

4 An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0.

So far nothing new I guess, so lets get it on:

6.8.5.3 The for statement

1 The statement for ( clause-1 ; expression-2 ; expression-3 ) statement

behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. ...

So we now know the body (in your case // Code) will be executed as long the beforehand evaluated value of your *p is not zero.

... The expression expression-3 is evaluated as a void expression after each execution of the loop body.[...]

So now we know, (I assume digging up p++'s definition is not necessary?!) that for each iteration p increments, so there may be a change in *p.

The following point is not related, but I'm adding it since this makes the Semantic part of for complete and its well to know since its the reason, why for(;;) is a inf-loop.

2 (---) Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

Ok, that's the dry but information-enriched part of what the for loop does in your case.

Now lets get over to pointer arithmetic:

6.5.6 Additive operators

Constraints

2 For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

So in your case you are adding 1 (integer) to the "pointer to an object"-type.

What is equivalent to increasing the Address by the sizeof its pointed to type like shown in this picture of tomislav kostic:

CC BY-SA 3.0 by tomislav kostic

Now lets see what *p actually does.

6.5.3.2 Address and indirection operators

Constraints

[...]

2 The operand of the unary * operator shall have pointer type.

Semantics

[...]

4 The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

This is a bit dry again1 but for better understanding this can be reverse engineered by:

6.5.2.1 Array subscripting

[...]

Semantics

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).

So *((p)+(0)) what is(since p+0 is same as p... obvious) is equal to p[0], is doing nothing else as evaluating p's object.

And since we know, expression-2 of a for loop is interrupting the iteration if it is evaluating 0, we can say it is the same as p[0] != 0.

Now the final step

Lets just look onto the C-Coder's Friend; JSSCA... No, wait...our friend was called... ASCII Now as that's clarified, we can figure out what the 0 is representing.

It is the NULL-token that in C is designating the end of a string.


So conclusive:

All, this is doing is:

Iterating the body of that for-loop, until p is actually pointing to the address, where the object evaluates to the "end of string"-token.

Or:

Let p go through the string until the end is reached.


And now just to cite my self; Something you never should forget:
(emphasis mine.....)

A variable is declared through a declarator(type-specifier) that precedes the identifier which names an lvalue object that can be evaluated to its value

It is neither more nor less!


1That is, what I promised! ;)

Share:
49,445

Related videos on Youtube

MeChris
Author by

MeChris

Updated on May 28, 2020

Comments

  • MeChris
    MeChris almost 4 years

    I don't understand what a pointer does in the for loop. What does the *p do in the following loop?

    char str[128] = "Some Text";
    char *p;
    
    for (p = str; *p /*what does this mean?*/; p++)
    {
        // Code
    }
    

    I do understand the rest, but why isn't *p like p > 3 or something like that?
    Why is it alone?
    Why is it written that way?

    • user3528438
      user3528438 over 8 years
      google for "c string".
    • user3528438
      user3528438 over 8 years
      actually c string terminator as search keyword is more helpful.
    • Prasanth Kumar
      Prasanth Kumar over 8 years
      The comparison has been omitted. It is *p != 0. 0 is the value which your char pointer points to when the string ends, because it is the string terminator. See this question for more details, in particular whether to use 0 or '\0'.
    • fuz
      fuz over 8 years
      @DanielDaranas *p behaves equally to *p != 0 in this case as for only cares if the value is nonzero (i.e. not a NULL pointer).
    • Dmitri
      Dmitri over 8 years
      @FUZxxl *p or *p != 0 dereferences p... so it's not checking for a NULL pointer, but whether it points to a value of zero.
    • fuz
      fuz over 8 years
      Yeah, should have been “resp.” instead of “i. e.”
    • Prasanth Kumar
      Prasanth Kumar over 8 years
      @FUZxxl I know. It behaves equally. That's why I said the comparison "has been omitted". And no, it is not checking for a NULL pointer at all.
    • M.M
      M.M over 8 years
      having X as the second condition is equivalent to (X) != 0, for all X.
    • holex
      holex over 8 years
      *p in this context in the for-loop means: please do it until the pointer is nil, as the string is closed by \0, obviously the loop ends when the cycle reaches the end of the string.
    • haccks
      haccks over 8 years
      Is this bounty just for creativity or you need some additional information? @Ike
    • Admin
      Admin over 8 years
      @haccks I'd be amazed if you could contribute new info! I'm judging the bonuses as lesser to the educational value of answer, they're superficial challenges that hopefully prevent answers from becoming too simple or quick (and also hopefully a little fun to read/write -- C tag has gotten a bit dull lately). If you think you can contribute new info (ex: assembly breakdown maybe, compiler design perspective, history, anything?) I'd be really impressed to say the least.
    • haccks
      haccks over 8 years
      OK. On SO I am among lazy guys, but will try to add some additional information with some creativity :) @Ike
    • Weather Vane
      Weather Vane over 8 years
      @Ike I am surprised you are awarding bounties, and changing the conditions, before the period is even closed.
    • Admin
      Admin over 8 years
      @WeatherVane Felt bored and generous over the holiday season. :-D But even with this kind of basic question, the diverse characteristics of the answers surprise me quite a bit. Hence the rewards for surprising me with each new bounty. I wanted, as an experiment, to see if we could get interesting answers out of a basic question with a few forced constraints that require people to take some time in answering.
    • Weather Vane
      Weather Vane over 8 years
      @Ike that's generous, but you didn't seem to notice my answer ;( I know Kaiku does not usually rhyme, but I can't quite divorce myself from limerick abilities.
    • Admin
      Admin over 8 years
      @WeatherVane I did! ... And up-voted it. Though you missed the timing by a little bit -- apologies for that! But I'm keeping this last one open for the extended duration (running out of rep), hopefully that will help more people notice your fine answer.
    • Weather Vane
      Weather Vane over 8 years
      @Ike thankyou but -- oops "Kaiku" -- that's me down even though it rhymes with "Haiku", but is not supposed to.
  • MeChris
    MeChris over 8 years
    Thanks a lot! Explained very very well. I was really confused because pointer was alone there.
  • Jonathan Leffler
    Jonathan Leffler over 8 years
    Note that by definition, a string is a sequence of zero or more non-null bytes terminated by a null byte.
  • Admin
    Admin over 8 years
    This answer has great potential, but I feel like it's missing a picture, a quote from Knuth, one from Ritchie, and one from yourself (in italics). That would definitely get my bounty, since you already have a cool hat.
  • M.M
    M.M over 8 years
    *p != NULL is not equivalent to the others. NULL may be defined as (void *)0, which means this is a comparison between integer and pointer. This comparison requires a cast unless the integer is a null pointer constant , which *p is not (even if it happens to hold value 0). See C11 6.5.9/2 for reference (earlier versions of C have a similar rule).
  • M.M
    M.M over 8 years
    The diagrammed text *p = NULL is incorrect; this should be *p = 0 or *p = '\0'
  • Manos Nikolaidis
    Manos Nikolaidis over 8 years
    @M.M You are correct. I erroneously remember seeing it used like this but actually it was NUL (non-standard).
  • Admin
    Admin over 8 years
    This post really seems to be the perfect answer. I'm forced to wait a little longer before I can award the bounty, but it is so close to perfect! The only thing missing is a personal and original quote from yourself -- some one-liner perhaps which captures your philosophy on this subject and stands out (could be poetic and just about programming in general or the life of a programmer or anything like that, or it could be about C, about pointers in general, about expressions, etc.).
  • Joe
    Joe over 8 years
    No problem. In all reality there's not much difference, but it's worth noting here as it is a piece of history that people come across, particularly with nasty code like the OP showed.
  • user4815162342
    user4815162342 over 8 years
    Using *p in a boolean context is not poor code, it is a standard idiom all C programmers are familiar with.
  • Admin
    Admin over 8 years
    @user4815162342 @Joe Perhaps it is a risky territory to suggest is to be a poor style. I've personally never used it in this context since I wasn't sure I could, with the widest portability, assume '\0' == 0. But those who know that for sure, or perhaps if that is guaranteed by the language standard, might very well use that shorthand justifiably.
  • Joe
    Joe over 8 years
    I agree it is idiomatic C but I disagree that it is good code. The idiom does not make it more reliable, more maintainable, faster or less coupled. Certainly it should be understood, but I'm not sure it should be perpetuated.
  • Manos Nikolaidis
    Manos Nikolaidis over 8 years
    @Ike not good with poetry or philosophy I am afraid :-( I did add a pun though.
  • Admin
    Admin over 8 years
    @ManosNikolaidis That is perfect! Now I just have to wait 11 hours, but this answer is, by far, my favoritest one.
  • user4815162342
    user4815162342 over 8 years
    It is generally considered that treating terminators such as '\0' and NULL as false values makes the code more readable. It is not only idiomatic C and C++, but endorsed by the language authors in The C Programming Language. Furthermore, "logical truth" continues to be present in mainstream languages created after C, such as Python, Perl, Ruby, or JavaScript. While it is not unreasonable to question any particular coding style, given the volume of existing practice, in this case the burden of proof is on the questioner.
  • Admin
    Admin over 8 years
    @ManosNikolaidis I upped the antes though. Now there's a 100-point bounty on this Q.
  • Admin
    Admin over 8 years
    Please note that there's a 100-rep bounty on this question.
  • Admin
    Admin over 8 years
    This is amazing! I feel like it is a strong candidate for the new bounty. But I feel slightly like I am reading an answer from Spock. I would love to see some more humor, a personal view on the subject, a philosophy or some poetry (maybe a haiku or this subject). Think Butt-Ugly Fish Book. I really feel like this answer has great potential for this new bounty though -- also could use some headings and/or bullet points. If you can somehow cite Jessica Alba, it would be so perfect (though optional).
  • Admin
    Admin over 8 years
    If you look at the previous answer that won the previous bounty, it had an "I C the point" joke in it which really biased me towards it. But it doesn't have to be humorous, it could be philosophical, just a quick personal story about when you started learning C, something to that effect. -- anything that gives it a more human touch.. oh and don't forget big, bold headings. Those really stand out.
  • Admin
    Admin over 8 years
    About the personal quote, the citation doesn't have to be so blatant. You could just have a new line, italicized. Of course ideal would be like, "I like cheese!" -- Ike -- this kind of format, maybe with a footnote using <sub> </sub> below it stating that the bounty made you do it if you feel uncomfortable about citing yourself.
  • Admin
    Admin over 8 years
    Now if you are having difficulty imagining how to possibly go the extra mile and cite Jessica Alba, some hints.... think about how she is very beautiful, toned, graceful, firm, perky, cute, small, a dancer... these kinds of characteristics should be easy to tie to C, and why it's still around in spite of all these other languages.
  • dhein
    dhein over 8 years
    @Ike: I'll try my best over the day. But I'm kind of humor handicaped so I'll probably have trouble with that. But maybe I'll be able to make something out of the fact itself. '^.^
  • dhein
    dhein over 8 years
    Note there is nothing evaluating to false regarding to a for loop. Have a look on my answer, the standard just simply says the 2nd expression has to be scalar-type and is interupting the iteration when its evaluated value is zero. so even if using stdbool.h, it is false what evaluates to 0 to interupt not vise versa ;)
  • dhein
    dhein over 8 years
    @Ike For now I changed my Profilpicture into a stone just designed for you and therefor a perfect fitting head. Isn't that awesome anyway?:D
  • Admin
    Admin over 8 years
    Oh wow, definitely bonus points for the hat and avatar. I think this is the strongest candidate for the new bounty, by far. My most immediate suggestion to improve it a bit is to break up the text a bit into sections through headings. We want to add some flash in there, make the info pop out, since otherwise people might overlook this gem.
  • dhein
    dhein over 8 years
    @Ike: done so far. And a cite of my own is incomming soon. Just looking for something I'm really expressing very often about C and I hope I'll find a highvoted post of me containing it to refere to :P
  • Admin
    Admin over 8 years
    How'd you get so comfortable navigating your way around the ISO/IEC standard documentation? Do you have a printed version around that you can skim through from time to time? BTW -- awesome edit!
  • dhein
    dhein over 8 years
    I don't want to be pedantic, but first of all, there is no such thing as an "unity" operator in C. Especially not if you are refering to the pretty old ANSI C. Also I would love to check your quote that it was realy D. Ritchie who said/wrote "The unary operator * is the direct or deferencing operator; when applied to a pointer, it access the object the pointer points to." But the url you link to it with is simply... not even an url. Well I have to admit, your pictures and styl is pretty entertaining, well done. But the content it self is bad cited, incomplete and partial even incorrect.
  • dhein
    dhein over 8 years
    @Ike: sorry, I'm not quite sure I got that question right. Are you asking how I'm able to navigate my self that well through the document? (if so, thanks for the compliment, if not, could you rephrase the question?)
  • Admin
    Admin over 8 years
    Oh sorry, I mean I noticed in your answers in general that you seem to have the uncanny ability to cite the ISO standard for many topics. I've never been able to do that -- it would take me ages to find the relevant section, so I was wondering if you have a printed copy that you kind of browse through from time to time, improving your familiarity of where relevant information is located in the document.
  • dhein
    dhein over 8 years
  • terence hill
    terence hill over 8 years
    Citation are in fact not link, just citations, but they are wrong as I saved them as links. Thanks. Unity it's a typo, thanks again to point it out, should be unary. The quote is from pag 94 of the C Programming Language. If you think that there are some other errors I appreciate if you can point them and I will try to correct them, I admit that I focused more on the entreating as well done and correct answers are already here.
  • dhein
    dhein over 8 years
    I belive you that it is in the book. But I'm not academic enough to say is it important to know which author wrote what or if 2 authors wrote one book you jsut can take one of them and assume he was it? IDK. But acording to the part you focused on: well done ;)
  • dhein
    dhein over 8 years
    @Ike: And there is the cite to my self :P
  • Admin
    Admin over 8 years
    OMG, this is a magnificent answer and it actually has an embedded picture of Jessica Alba! Bravo! I don't know what to do now -- there is some tough competition going on between you and Zaibis! I feel like your answer is better suited for the beginner level of the question, but Zaibus has that dead-on technical precision. In any case, whatever happens, both of you are winners in my eyes!
  • Admin
    Admin over 8 years
    @Zaibus OMG, there is a fierce competitor who actually embedded a picture of Jessica Alba! I believe you have the edge when it comes to technical precision, but there is some competition brewing. Maybe it would help to also embed a picture of Jessica Alba with text along side of it?
  • dhein
    dhein over 8 years
    @Ike: Well, what you are going to do is absolutely your decision. ;) I like my letter gambling from ASCII to JSSCA and I'm really not good in intersocial stuff like humorfully representing a picture of some one expressing something or such. Also remember your actuall wording just gives "bias" to the Jessica Alba part ;P
  • Admin
    Admin over 8 years
    While my bounty is encouraging very detailed questions with headings and stuff so that they might educate a wide range of people and also give them more stuff to look up, this answer is pretty nice... short and sweet, and noteworthy in its conciseness. My only gripe is that it can be provided quite rapidly. But it is a wonderful answer nevertheless -- bravo!
  • terence hill
    terence hill over 8 years
    @Ike wow, thanks for the comment, but especially for this funny game. I really enjoyed myself answering. I updated my answer, hope you will like it even more.
  • Admin
    Admin over 8 years
    @terencehill I think I'm leaning towards Zaibis' answer, since his has a very unusual characteristic -- but I'm chaining a bounty right after that which rewards fun factor and beginner-level appropriateness which has your name all over it.
  • Admin
    Admin over 8 years
    @terencehill New bounty that currently has your name all over it!
  • Admin
    Admin over 8 years
    @terencehill There is one new bonus challenge with the higher bounty which could give your answer the uber dominating edge (though it already has this for the most part) -- it is to include a haiku on the subject, 5-7-5 syllable form (not strict adherence beyond the syllables to the formalities of Haiku) -- just formatted that way.
  • Admin
    Admin over 8 years
    I think your answer (besides Haiku) part could be even more awesome if the for(;C;) awesome joke was for(;*C;) to tune it for this question, though up to you -- props either way. One thing that might help is to put a comment in that while loop code version, especially around the while(*p) part.
  • terence hill
    terence hill over 8 years
    Yes I also thought about the *C but was in doubt.
  • terence hill
    terence hill over 8 years
    @Ike I'll start thinking about the Haiku from my copy of "Goedel, Escher, Bach".
  • chqrlie
    chqrlie over 8 years
    @Ike: it would be even better if ManisNikolaidis would add a third line with a hex dump, to illustrate how characters are encoded in memory and how a null character, spelled '\0' and encoded as 00 terminates the string.
  • chqrlie
    chqrlie over 8 years
    -1. Sorry but NULL is not the null character, '\0' is. *p != NULL will fail to compile on most C environments because NULL is the null pointer and as such usually defined as ((void*)0). C++ defines NULL as 0, thus lets one write such confusing horrors as *p != NULL. Don't do it.
  • Admin
    Admin over 8 years
    OMG, I am giving this an up-vote from the rebel side (thinking I shouldn't) -- as both a C and C++ developer, but appreciating the C aesthetic a lot of minimalist elegance. This is an interesting stylistic angle -- props for its daring nature.
  • Admin
    Admin over 8 years
    This answer is terrifying to me in terms of its sheer (and great) boldness -- I feel the need to cast protection against potentially angry C++ devs. To those viewing, keep in mind that this contributes a totally unique aesthetic angle to the question, that experience causes us to diverge in aesthetics, and even through the choice of languages we use. This is an idiomatic C aesthetic. And, at the end of the day, the only thing that matters is results -- look at Linus Torvalds, he despises C++, and we can't argue with the magnificent results he achieved nevertheless.
  • terence hill
    terence hill over 8 years
    I'll follow you thru the dark C++, we'll defeat the templates to C the *.
  • J. Sy
    J. Sy over 8 years
    I meant NULL is ascii NUL (0) character here. Sorry for the confusion by mixing NUL character and NULL pointer.
  • dhein
    dhein over 8 years
    Funny +1 from me aswell. But remember, even this is a nice idea, remember this is still SO with its on- and off-topics. It feels difficult for me to see a real answer in it. :/
  • dhein
    dhein over 8 years
    absoloutly wrong! your description of an for loop is simply incorrect. It is the way it is usually used. BUT you are simplyfing it in a way, that just excludes its mainfeatures and anyway the wording itself is dim in regards to the expressions you used.
  • Samidamaru
    Samidamaru over 8 years
    Come on guys where are these haikus: First p equals str, Then p is incremented, Until *p is NUL.
  • Samidamaru
    Samidamaru over 8 years
    @Ike & terence hill, if you want to use that, I'll accept a reference and weekly payments to my paypal account: [email protected]
  • Admin
    Admin over 8 years
    @Zaibis & machine_1: keep in mind though that this is an absolute beginner-level discussion (though Zaibis' post might teach even pros a thing or two). We tend to simplify a lot, like when teaching a child about how babies are born. For machine_1, perhaps a good way to avoid getting into trouble with the oversimplification is to qualify that this is what the code the op posted logically means from a human perspective in this context, and is not a technical breakdown of how a for loop generally works.
  • Admin
    Admin over 8 years
    @Zaibis It's focused from a stylistic perspective of why the code might be written in such a way in C, which does address the part of op's question about why it is written that way. There's also a brief answer there about the logical behavior of iterating through to the end of the string. Some variety in answers is a good thing for future readers as I see it (redundancy would be terribly dull and time-consuming to read through), even if there can only be one accepted!
  • dhein
    dhein over 8 years
    @Ike: I have no trouble with simplyfications in generall and I even could live with the first expression beeing called initialization. but the 3rd beeing degraded to "increment" is simply not correct!
  • dhein
    dhein over 8 years
    @Ike: I don't want to say anything bad about this. But you can't deny that this is on the edge to off-topicness. Just said, to improve it somehow so it isn't too close to this edge anymore ;)
  • Admin
    Admin over 8 years
    @Zaibis For sure, though perhaps machine_1 was specifically just trying to describe what's meant logically by for(p=str; *p; p++), in which case his answer is no longer so inaccurate (describing things in terms of human logic, and just for that one piece of code). So my suggestion to machine_1 is to edit and make that qualification, that this is describing what the code does, and not at all a general for loop. That would make this acceptable to you, no?
  • Admin
    Admin over 8 years
    @Zaibis It is dangerously close -- though I think it's only really clear that questions that blatantly call for subjectivity are OT, not subjective answers. Maybe one way to look at this is that this describes a C aesthetic -- embracing it is subjective, but languages and aesthetics aren't divorced from each other. To embrace a C++ mindset wholeheartedly often requires somewhat disliking some of the lack of safety in C, e.g., while embracing C wholeheartedly often requires seeing a lot of these mechanisms in C++ as obstacles to get closer to the bits and bytes of the machine.
  • dhein
    dhein over 8 years
    @Ike Thats true but that is exactly the point with or without headline. Because it is something opinion based (you see even in your first comment's reactions). And that is something what is strictly tryed to be avoided on SE. got me? edit to your second comment: the point is the way you give by bount every time new aspects to a OP is kind of out of the SO scope. So hard to categorize it. But dont try to convince me I'm fine. Just noted it so you all are aware and OP may edit.
  • Admin
    Admin over 8 years
    @Zaibis Agreed -- though I'm unclear on whether a subjective leak in an answer warrants it as OT. I think the reason POB questions are OT is in an attempt to discourage too much subjectivity in the answers (not to avoid them outright with an iron hammer, since most of us would have great difficulty there answering anything, though you might be able to do it perfectly!). But if an answer chooses to do it anyway, I think it's in a gray zone which puts it more in the voting rather than flagging territory. Oh well, this might be like a meta topic! :-D But for now, I think this answer is fun!
  • Admin
    Admin over 8 years
    BTW, have you ever read the Butt Ugly Fish Book? amazon.com/Expert-Programming-Peter-van-Linden/dp/0131774298‌​. It might not suit your taste as it's a book on C filled with anecdotes and little jokes and stories everywhere. But it's a nice example to me of how something can be fun and actually very educational and reasonably precise all at once. From this little bounty game I'm playing, it was originally inspired by boredom -- but I used to teach computer science in the early 2000s. I'm hoping the resulting Q&A will show that even the most basic question doesn't have to...
  • Admin
    Admin over 8 years
    ... require simple, routine answers, that even a basic question can tackle complex subjects and territories a lot of people aren't aware about if we want to take them as technically far as you do, or as fun as some others took it -- and fun sometimes is a prerequisite, at least for some students, to help them learn subjects without being bored. There's a very diverse range of learning styles out there -- from visual to mathematical to very technical and literal -- lots of people benefit from different styles. And I'm hoping the variety in these answers can show that to future readers.
  • terence hill
    terence hill over 8 years
    @Samidamaru let me know if i may join your circle of Msters!
  • terence hill
    terence hill over 8 years
    @ike updated answer with the haiku. I tried my best but I am not even sure about the syllable (as a non-english that was hard, I realised for the first time that I have no idea how syllable works in english).
  • Admin
    Admin over 8 years
    @terencehill Perfect! I'm going to leave the bounty going for this one quite a bit since it's starting to cost a lot of rep -- but mostly so that the question gets viewed. I think it would be very difficult to beat this answer, plus I couldn't stop laughing for hours the first time I saw the Jessica Alba pic. :-D
  • terence hill
    terence hill over 8 years
    @Ike thanks, corrected. Yes, let it be ;). I hope we can see more answers (the one from chqrlie is really fantastic) and more comments like the one above from Samidamaru.
  • Admin
    Admin over 8 years
    OMG, I have to wait a couple of hours to +1 (exhausted my votes), but did you make that animation yourself? And if so, how???
  • haccks
    haccks over 8 years
    @Ike; Yes of course. Actually I am on bed rest theses days so have plenty of time. Created 36 images for this gif :)
  • Admin
    Admin over 8 years
    I feel like I have to make another bounty just for this answer -- as I think it has the most educational value I've seen yet.
  • haccks
    haccks over 8 years
    @Ike; Thanks for your appreciation. I am glad you really liked it.
  • Admin
    Admin over 8 years
    Have all my up-votes! I taught CS 101/102 for a brief period in my life (late 90s) so I think this is one of the most effective ways to teach people out there (always wished I could draw animations on a whiteboard). This doesn't quite fit my current bounty requests but I think I'll make another one just for this after for the most educational answer. I've always wanted to do more visual answers like this to explain topics but was always too lazy.
  • Admin
    Admin over 8 years
    I made a new bounty which is pinned to your answer. I want to let the timer run out on that one to give all of these people who contributed answers as much exposure as possible, but this bounty is reserved for this answer for surprising me so much with an animated GIF answer to the question.
  • terence hill
    terence hill over 8 years
    Wow! Now I feel like I have to make jessica speak :P
  • dhein
    dhein over 8 years
    By the way: where is your quote from? Can't find it in any of my standard copys.
  • haccks
    haccks over 8 years
    @Zaibis; It is quoted from c-faq. Link is attached there.
  • haccks
    haccks over 8 years
    So *p is pointing to successive elements of the array in each iteration.: I think you mean to say p, isn't it?
  • Weather Vane
    Weather Vane over 8 years
    @haccks I debated with myself which to use, I put *p in this sentence because *p refers to the array element's value, not to its address. Tricky to phrase perhpas? I'll edit it in a minute.
  • haccks
    haccks over 8 years
    Yup. *p represents the successive elements rather.
  • Weather Vane
    Weather Vane over 8 years
    @haccks thanks, I made a slightly different edit, so it remains my work ;)
  • haccks
    haccks over 8 years
    While explaining about pointer arithmetic you should consider the pic for character arrays. @Zaibis
  • Joe
    Joe over 8 years
    PLEASE do not edit this. I mean NUL. ASCII NUL, not NULL.
  • dhein
    dhein over 8 years
    @haccks: agreed. I'll see when I have the time for that.
  • terence hill
    terence hill over 8 years
    +1 For the Lyric! Well done. You may consider to enter our circle of Master Haiku Poets? And I also liked the citations from my dear friend Jessica.
  • holzkohlengrill
    holzkohlengrill almost 7 years
    this animation makes me dizzy xD
  • Henry
    Henry almost 7 years
    what if an actual '0' occurs in the middle of array?
  • haccks
    haccks almost 7 years
    @Henry; Then loop will stop at that 0.
  • Bojie Shuai
    Bojie Shuai about 3 years
    I try to achieve the same thing with a while(*p){...} loop, but the loop won't stop at the end of the str. There are more values after that. Is that because of the same reason you mentioned in the answer? (random values after the null character)