Ignoring other considerations for a moment and in general ...
Would there be a difference in result (dot oh or execution) of:
strncpy( a, b, sizeof(a) );
c = sizeof(a);
strncpy( a, b, c );
My general understanding is (at least I think my understanding is) that in cases where something is inherently fixed in size then the compiler inserts the literal value of the size of the item at compile time as opposed to leaving an implicit run-time function call.
If my understanding is correct then it seems in scenario A. we'd have strncpy( a, b, 4 ) in one line of execute compared to two lines in B.: c = 4; strncpy( a, b, c ).
Is that not correct?
Am I missing something?
Thanks in advance for any comments.
Long Valley, NJ
Last edited by GSalisbury; 12-14-2015 at 05:04 PM..
is wrong, but won't actually hurt you unless a contains more bytes than fit in an object of type signed int. If you're using an external object to store the results of the sizeof operator, its type should be size_t; not int.
Note that if you are in a subroutine that has been passed a pointer to an array of characters to be copied into an area of memory pointed to by another pointer to an array of characters, you have to be also be given the size of the destination array, as in:
You seriously don't need to worry about overhead of an extra line of code.
Lets do some rough guess calculation here...
What you got a 2GHZ processor? That's 2000,000,000 cycles per second.
Lets say that extra line adds 20 cycles on the program. That's a 10 millionth of a second.
Reading a few bytes from a disk may well take in the order of milliseconds.
If you think it makes the program clearer then do it. I routinely add extra steps and variables to make my code more readable and I deal with vast amounts of 24 hour streaming data.
And my stuff flies.
The original query was not overtly based upon concerns of overhead or performance per se but, rather, [possible?] quote technical differences in compiled result.
The illustrated fragments using sizeof as arguments were in place in an area that was already selective in execution and time and volume did not come into play.
A discussion had started on the merits of an argument vs. a variable and the posting here was more for enlarging the set of opinions. I, too, will often include additional steps etc. in order to make a sequence more clear or to be able to include some step-wise commentary.
The upshot was we (I) left the use of the sizeof as arguments in place as is principally because we (I<g>) didn't have to do anything (Management 101 - 1st precept - do nothing) and because the use was in a block that already well commented leaving no ambiguity.