Harald van D©¦k wrote:
On Sat, 18 Oct 2008 07:58:37 -0700, Mara Guida wrote:
Is there a suffix for size_t?
size_t is a typedef, not a built-in type.
Ah! Of course.
I got used to thinking of size_t as a built-in type.
I want to define MAX_LINE_LENGTH as a size_t.
Why do you want to do this? Does size_t offer anything of use for
constants that the default type doesn't? Depending on why you want this,
there may be other options.
I want to minimize the number of casts and warnings of my programs.
Some functions take a size_t as a parameter and with a plain #define
the compiler issues a warning; other functions take an int and
complain with a size_t.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LENGTH_AS_INT 80
#define MAX_LINE_LENGTH_AS_SIZE_T ((size_t)80)
int main(void)
{
char *data_int;
char *data_size_t = malloc(MAX_LINE_LENGTH_AS_SIZE_T);
if (data_size_t) {
/* warning: passing argument 2 of ¡®fgets¡¯ with different width
due to prototype */
fgets(data_size_t, MAX_LINE_LENGTH_AS_SIZE_T, stdin);
/* fgets(data_size_t, (int)MAX_LINE_LENGTH_AS_SIZE_T, stdin);
*/ /* ok with cast */
free(data_size_t);
}
/* warning: passing argument 1 of ¡®malloc¡¯ with different width
due to prototype */
data_int = malloc(MAX_LINE_LENGTH_AS_INT);
/* data_int = malloc((size_t)MAX_LINE_LENGTH_AS_INT); */ /* ok
with cast */
if (data_int) {
fgets(data_int, MAX_LINE_LENGTH_AS_INT, stdin);
free(data_int);
}
return 0;
}
I think it's better to cast a size_t to int, than the other way
around.
but I wonder if there's a more beautiful construct,
const size_t MAX_LINE_LENGTH = 80;
It has its own limitations: you cannot use this as a static array length,
for example. What do you want to do with MAX_LINE_LENGTH?
This looks good, thank you.
I'm going to try some variations with const too.