-Wconversion warning with htons

Yang Zhang yanghatespam@gmail.com
Sun Feb 22 22:08:00 GMT 2009


When compiling the following:

#include <arpa/inet.h>
int main() {
   sockaddr_in sa;
   unsigned short x = 3;
   sa.sin_port = (unsigned short) htons((unsigned short) x);
   return 0;
}

I get:

$ g++ conversion_weirdness.cc -O3 -Wconversion
conversion_weirdness.cc: In function ‘int main()’:
conversion_weirdness.cc:5: warning: conversion to ‘short unsigned int’ 
from ‘int’ may alter its value

The man page says the signature of htons is

   uint16_t htons(uint16_t hostshort);

I've been fiddling around with inserting casts at various places, 
declaring extra intermediate variables, using uint16_t, etc., but I 
can't seem to figure out what precisely is causing this warning.  Any hints?

Thanks.
-- 
Yang Zhang
http://www.mit.edu/~y_z/



More information about the Gcc-help mailing list