code in lib/os.c not clear to me

67 views
Skip to first unread message

Sha

unread,
Nov 9, 2017, 6:48:09 PM11/9/17
to lemon-lang


In this code under lib/os.c (lines 351-356):

#ifdef WINDOWS
  (void)buf;
  ptr = ctime(&t);
#else
  ptr = ctime_r(&t, buf);
#endif

What does (void) buf; this really do?

Thanks,
~ sha






 

Stefanos

unread,
Nov 10, 2017, 10:23:32 PM11/10/17
to lemon-lang
"(void) buf" silences buf so ctime() can use only t, but it's indeed something that needs clarification. 

ctime() accepts only "const time_t *timep" as its single argument, whereas ctime_r() acccepts "const time_t *timep, char *buf".

Maybe it's something that could get removed?

admin

unread,
Nov 11, 2017, 3:23:00 PM11/11/17
to lemon-lang

This is C Programming 101. You should grab any C programming book or google it.

admin

unread,
Nov 11, 2017, 3:26:34 PM11/11/17
to lemon-lang

Windows don't have safe version ctime like ctime_r, maybe newer Windows has, I haven't check, but lemon doesn't support thread, so It's same.

Sha

unread,
Nov 12, 2017, 8:58:33 PM11/12/17
to lemon-lang
Stefanos,

Thanks for the explanation. But I am still a bit confused... what does it "silence"?  Compiler warnings may be?

I see @zhicheng's comment that it is "C 101" so I am googling for it. My understanding is that it will matter only if there is an assignment or argument passing.

Just a free standing expression (void)buf; does not make sense to me (yet). I will keep on looking though.

~ sha
Message has been deleted

Stefanos

unread,
Nov 15, 2017, 11:24:36 AM11/15/17
to lemon-lang
The code is this:

static struct lobject *
os_ctime(struct lemon *lemon, struct lobject *self, int argc, struct lobject *argv[])
{
time_t t;
char *ptr;
char buf[26];

if (argc != 1 || lobject_is_integer(lemon, argv[0])) {
return lobject_error_argument(lemon, "required 1 integer argument");
}
t = linteger_to_long(lemon, argv[0]);

#ifdef WINDOWS
(void)buf;
ptr = ctime(&t);
#else
ptr = ctime_r(&t, buf);
#endif

return lstring_create(lemon, ptr, strlen(ptr));
}

If you are under Windows, then it the function will use ctime() which takes a single argument of type const time_t *.

As you can see buf is declared as char buf[26]; but under Windows it's never used, therefore will throw a warning about unused variable.

In order to compile our code by letting our compiler know it's okay to have an unused variable, we cast buf to type void to silence possible warnings.

To make things clearer for you, try the following code:

#include <stdio.h>

int main(void)
{
    int age = 100;
    const char * name = "old man";

    (void)name;
    print("I'm a %d year old...thing!\n", age);
    return 0;
}

Sha

unread,
Nov 17, 2017, 10:00:20 AM11/17/17
to lemon-lang
Great! Exactly what I had suspected ... that it was simply to silence compiler warnings.

Thanks so very much for such a detailed explanation, Stefanos.

~ sha
Reply all
Reply to author
Forward
0 new messages