-
sizeof
This is probably a religious question, but here goes:
Code:
struct something {
int x, y, z;
}
struct something *buf;
...
A:printf("something about size of *buf %i.\n", sizeof *buf);
B:printf("something about size of *buf %i.\n", sizeof(*buf));
...
SO, given the above, what is the general concensus about A vs B? Which way is the "right" way? Again, this is probably a religious discussion.
Andy
-
This depends on if you look at sizeof as more of an operator, or a function. I always preferred the latter. At any rate, I don't think there is a "right" way.
-
Personal preference I guess. There may be precedence rules that would necessitate the use of parenthesis in some cases. I always use them as if sizeof was a function. I know it's rather more of a compiler pre-processor thing and can be resolved early. But then why are parenthesis necessary for SWITCH statements, or IF statements if the statement is simple and unambiguous enough they shouldn't be necessary.
-
To muddle the issue further, you NEED the parentheses if the argument to sizeof is a type (as opposed to an expression). This is not valid C:
Code:
int n = sizeof int;
Yet another reason to prefer the parentheses, because it works for both types and expressions.
-
I used to use parentheses all of the time, but there's a certain quality of laziness in being able to leave them out. :) Sometimes it can also make your code more readable if you already have a few levels of parentheses.
You just have to keep in mind that parentheses are required for types, as mentioned. But usually I think that if you're taking the size of a type you're not doing something correctly. Either take the size of a variable or use limits.h. :)