Re: Sequence point doubt



In article <47419cea$0$4790$426a74cc@xxxxxxxxxxxx>,
Spoon <root@localhost> wrote:
Hello,

Is the following code valid:

char buf[1024];
int size = 666;
size += sprintf(buf+size, "%d", size);
size += sprintf(buf+size, "%d", size);

(Expected behavior: at offset 666, buf contains "666669\0".)

Is it equivalent to the following code:

char buf[1024];
int size = 666;
int temp = sprintf(buf+size, "%d", size);
size += temp;
int temp = sprintf(buf+size, "%d", size);
size += temp;

AFAIU, the function call is a sequence point, therefore size can only be
updated after sprintf has been evaluated with the "old" value of size.

That's correct, though the reason I'd give is that both of the places
where size is evaluated in the sprintf call are used to determine the
value that is eventually stored into size (they're needed for the call
to sprintf, and the return from sprintf is added to the old value of
size).


This reasoning might be incorrect if sprintf were a macro, right?
(Can it be?)

Any standard library function is allowed to be a macro, but in most of
them are required to act enough like functions that you don't usually
need to care about the difference.

The only thing I can think of is that the return value doesn't depend
on the buffer you ask sprintf to print into, but I can't come up with a
reasonable macro implementation that would break this. So I'll go
ahead and claim that this is well-defined in every possible case,
secure in the knowledge that the language lawyers who have finished
their morning coffee will give several examples that will prove me
wrong.


dave

.



Relevant Pages

  • problem with strerror
    ... then recognize that this news group may be more appriopriate for this ... int SendWithLog(int sock, char * data, int length) ... I 've tried to call to strerror before the line sprintf, ...
    (comp.unix.programmer)
  • Re: Sequence point doubt
    ... Is the following code valid: ... char buf; ... int size = 666; ... (Expected behavior: at offset 666, ...
    (comp.lang.c)
  • Re: How to convert an integer to ASCII character ?
    ... I tried with sprintf(). ... static void putdecimal(unsigned int v, char **s) { ...
    (comp.lang.c)
  • Re: right padding
    ... I've tried with sprintf but I can only left pad with "0" or right pad ... char *pad(char *s, int n, size_t width, int padch) ...
    (comp.lang.c)
  • Re: Convert a binary value to unsigned decimal value
    ... Where will the sprintf write to? ... string represantation of an int, ... It's almost certain that char on your machine is 8 bits. ... > memcpy() ing a value into an unsigned char doesn't sound like the way to go. ...
    (comp.lang.c)