3

Noob C questions incoming:

#include <sys/types.h> 
#include <sys/socket.h> 
#include <netdb.h> 
int 
getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res)

void 
freeaddrinfo(struct addrinfo *ai)

Taken from http://www.nxmnpg.com/3/getaddrinfo. Namely I'm interested in why it isn't just getaddrinfo(char *hostname) and is a const instead.

I have an idea what a pointer is. It seems to me that almost all of the functions in C prefer pointers passed to just variables, is this correct?

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
dsp_099
  • 5,801
  • 17
  • 72
  • 128

2 Answers2

3

The const qualifier is a contract the function is making with you ensuring you that it will not change the value of any const arguments passed to it. This can be verified by the compiler so it's a good way to add extra safey and reassurance for you at the end of a long morning (;

dcow
  • 7,765
  • 3
  • 45
  • 65
  • Plus, in certain cases it can allow the code generator to perform additional optimizations. – Ignacio Vazquez-Abrams Apr 14 '12 at 04:26
  • 2
    @IgnacioVazquez-Abrams: `const` in C doesn't provide much of anything for optimizations. Aliasing issues generally prevent a compiler from assuming that a pointer-to-const won't change, and as far as non-pointer related `const` goes - if a variable isn't changed in a function, the compiler is generally free to optimize it the same way, whether it's annotated as `const` or not (in other words, `const` doesn't add anything as far as optimizaibilty goes). – Michael Burr Apr 14 '12 at 07:24
1

C doesn't have the concept of a string as a basic type; it's an array of (char), which can only be passed to a function as a pointer to (char). You will also see (long) passed as a pointer in older APIs, dating back to when many of the CPUs on which C was implemented couldn't pass a (long) in a register (thus couldn't be returned).

geekosaur
  • 59,309
  • 11
  • 123
  • 114