Basic C Questions

Status
Not open for further replies.
The fact that I've found 6 errors in the first 50 pages of the text book, might suggest that my confusion is the book's fault, but here we go.

1)


The book explains that dividing by negative integers, e.g., 16/-3, results in varying values, depending on the compiler and should be avoided; all other examples in the problem set where the denominator is negative are considered 'invalid.'


If
Code:
#define PI 3.14159
...
double x, y;
...

where y= -1.0, why does the textbook list the answer to the expression

Code:
x = PI / Y;

as -3.14159?

I know that PI is a character string, not an int. Is that why the value is -3.14159?


2) In the following:

Code:
scanf("%lf", &miles);

The text book describes '&' as the address-of operator, which tell the scanf function where to find each variable in memory into which the new value will be stored. If '&' is omitted scanf would know only the variable's current value, not its location in memory, which would prevent scanf from storing a new value.

Can someone explain in more detail? I understand what '&' is doing, but not how. (It's possible that this might be a question I just won't understand now, so that's OK if that's the case.)

3) The book also says the following about scanf:

"If you type more data characters on a line than are needed by the current call to scanf, the extra characters will be processed by the next call to scanf."

The book seems to be implying that extra characters somehow hang around (in memory?) until the next call to scanf. It makes no sense to me that these orphan characters would somehow be processed by the very next call to scanf, regardless of what else I might be specifying as input for the next call.

Can someone clarify what happens to extraneous characters if they aren't processed in the current function call?

Thanks.
 
A few answers:

1) The #define directive does indeed define 3.14159 as a string, However that string is used before compile time. The preprocessor takes all the defines and includes and effectively builds a new source file to be compiled. In your case, the compiler would see the line

x = 3.14159 / y; NOT x = PI / y;

Hence 3.14159 is just used as a typed in constant.

2) When passing variables to functions the value of the variables is copied onto what is called the stack. The stack grows each time a function is called so that each function call has its own set of memory. Thats why if you want to change the value of a parameter you need to pass the address so that you can change the values original value instead of the value generated on the stack. If that makes sense?

3) All characters read in are all stored in memory. Its called the input buffer. Keystrokes always get put into it, and then the routines that do input read off the front of the buffer. If you never call scanf again and characters are still in the buffer, they will just sit there until the next input occurs (I think the shell would read them in if working in a command line environment).

I hope these answer your questions.
agent145
 

gaffa

Well-known member
6,210
I will try and clarify point 2 (hopefully).
When a function or procedure call is made, the arguments (together with the return address) are pushed onto the stack. If they are passed by value (no &) then the value of the argument is pushed onto the stack. If they are passed by reference (with &) then the address of the argument is pushed onto the stack. If you then change an arguments value, the value is either changed on the stack (if passed by value) or the value addressed by the value on the stack (passed by reference) is changed. So when an argument is changed, when passed by value, the value does actually change on the stack, but then this value is not easily accessible after the stack has been unwound, as a result of the function or procedure returning to the caller. I hope that this has made it clearer.

BTW some flavors of C will sometimes implicitly pass some arguments by reference. For example, arrays and functions.

Cheers

Gaffa.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by agent145:
2) When passing variables to functions the value of the variables is copied onto what is called the stack.
Originally posted by gaffa:
When a function or procedure call is made, the arguments (together with the return address) are pushed onto the stack.

Yuck. Yuck. Yuck.

I really think it's better to explain parameter passing whithout reffering to this "stack" thing. Consider that if there are not too many arguments, they're passed in registers. And the return address nearly always gets a register.

gaffa, C is always call-by-value. What is tripping you up is the answer to the question "what is the value of an array" and "what is the value of a function".
 
The book explains that dividing by negative integers, e.g., 16/-3, results in varying values, depending on the compiler and should be avoided
The reason for this is that integers can be signed or unsigned. If you attempt to divide an unsigned integer by a signed one... well... you're in for trouble. Try to keep signed integers together, and unsigned ones together. With floating point numbers this is irrelevant as they are always signed.

Edit: I think that the example you gave should still work as integer constants are assumed to be signed if nothing else is specified.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by euzeka:
The reason for this is that integers can be signed or unsigned. If you attempt to divide an unsigned integer by a signed one... well... you're in for trouble.

Nah, the arithmetic conversions take care of that. The problem is: do you round a negative result toward or away from zero?

In Java (for instance), integer division rounds toward zero. C leaves this unspecified (so it can be implemented as a single machine instruction on many architectures).
 

gaffa

Well-known member
6,210
I really think it's better to explain parameter passing whithout reffering to this "stack" thing. Consider that if there are not too many arguments, they're passed in registers. And the return address nearly always gets a register.

gaffa, C is always call-by-value. What is tripping you up is the answer to the question "what is the value of an array" and "what is the value of a function".

If the first paragraph is true, what do you do when function or procedure calls extend to many levels, or a function calls itself recursively? You will run out of registers very quickly. You will be telling me next that automatic variables always go in registers as well.

In the second paragraph, this may be true of the C compilers that you have used. The DEC and VAX C compilers (now COMPAQ) implicitly pass the address of arrays and functions if the array is without brackets or the function is without parentheses:

char test_string[] = "Just testing";
.
.
.
printf("Contents of test string are: %s\n", test_string);


Cheers

Gaffa.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by gaffa:
If the first paragraph is true, what do you do when function or procedure calls extend to many levels, or a function calls itself recursively? You will run out of registers very quickly.
That's just a register allocation problem.

I never said that every argument would be able to go in a register. However, it is realistic to expect a compiler for a RISC processor to pass any reasonable number of arguments in registers. When your register allocator detects an interference, it's got to spill some registers. I'd hate to think we always spilled, even when there were plenty of registers available.

In short, you spill registers to the stack only when you've got to put something new in that register right now and you'll need the old value later. If the first of those conditions fails, you can leave the value in the register. If the second fails, you can discard the old value.

You are thinking of a world where 1) there are only caller save registers and 2) all arguments are saved before a call, even if their register is not live after the call. It ain't so. Don't feel bad, I've said before that "what the compiler does" is not the right way to understand programming languages.

You will be telling me next that automatic variables always go in registers as well.
Darn tootin'. I expect them to, as long as there are registers available.

In the second paragraph, this may be true of the C compilers that you have used. The DEC and VAX C compilers (now COMPAQ) implicitly pass the address of arrays and functions if the array is without brackets or the function is without parentheses:
Err, that's what I said. Again, what is the value of an array? What is the value of a function?

I cracked out K&R to see:

In preparing for the call to a function, a copy is made of each argument; all argument-passing is strictly by value. [Ref. Sec. A7.3.2]

If the type of an expression or subexpression is "array of T," for some type T, then the value of the expression is a pointer to the first object in the array, and the type of the expression is altered to "pointer to T."... Similarly, an expression of type "function returning T," except when used as the operand of the & operator, is converted to "pointer to function returning T." [Ref. Sec. A7.1]
Bolding is mine.
 
Originally posted by gaffa:
If the first paragraph is true, what do you do when function or procedure calls extend to many levels, or a function calls itself recursively? You will run out of registers very quickly.
And? All he said was that arguments aren't necessarily passed on the stack. Which is true.

Even if a function is called recursively, this is true. That is, if a function takes two arguments, and is declared such that they're passed in registers, they'll be passed in registers each and every time, even if it recurses a million times. How does it cope with this? Well, it pushes the registers onto the stack before calling the function, then puts the new values it wants to call into the registers, then calls the function. The caller is responsible for freeing up the registers so it can do this, the callee doesn't have to worry about it.

You will be telling me next that automatic variables always go in registers as well.
I'd certainly hope so, as long as there were enough registers.

In the second paragraph, this may be true of the C compilers that you have used. The DEC and VAX C compilers (now COMPAQ) implicitly pass the address of arrays and functions if the array is without brackets or the function is without parentheses:
No, it is true of all C compilers, and always has been.

char test_string[] = "Just testing";
printf("Contents of test string are: %s\n", test_string);
And...?

The value of an array is the address of the first element. This value is what will get passed to <tt>printf()</tt>. The array is passed by value. The confusion here is that you think that the array's value is "Just testing". It isn't.
 

gaffa

Well-known member
6,210
The topic was started by someone who is learning C. I posted, in the hope that I was helping him. I obviously wasn't. So in your capacity as moderator, Peter, can you delete my unhelpful post.
You and newton_meter can then switch off the optimizer in your C compilers, and give the guy a hand, instead of trying to confuse the hell out him, with your one-upmanship.

Cheers

Gaffa.
 
Originally posted by gaffa:
The topic was started by someone who is learning C. I posted, in the hope that I was helping him. I obviously wasn't. So in your capacity as moderator, Peter, can you delete my unhelpful post.
No. And there's no reason why you might not learn from this too (for instance, by rectifying your incorrect belief that C can do anything other than pass-by-value; it can't, it's much like Java in that regard).

You and newton_meter can then switch off the optimizer in your C compilers,
Passing arguments in registers isn't an optimization issue, it's a calling convention issue. It's not something the compiler is free to pick and choose.

and give the guy a hand, instead of trying to confuse the hell out him, with your one-upmanship.
No-one is trying to do that. They are trying to ensure that people describe things in accurate terms.

<hr />

The reason you need the <tt>&</tt> transcends issues of passing variables on the stack vs. in a register, and discussing the stack somewhat misses the key issue (as it doesn't matter where the variables are copied to, merely that they are copied).

C passes all values to all functions by value. What this means is that, when you call a function:
A set of variables matching the variables in the function's argument list is built
The value of each argument you pass to the function is copied into this new set of variables
The function is run using this set of variables

The function can see the value of each variable, but that is all. It can't modify the original variable, because it doesn't know where it is -- only what its value is. This prevents it from being able to modify the original variable -- any changes it makes to the variable only modify the copy of the variable, not the original. Furthermore, when the function exits, its set of variables will be destroyed, as they're no longer needed.

To get around this, you can pass the address of each variable to the function. This is still pass-by-value, but instead of the value of the actual variable, it passes the value of the address of the variable.

This is useful, because it allows the function to modify the data stored at that address -- it can write to the location the address refers to, and when the function exits, that location will still exist.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by PeterB:
[snipped explanation]

See, that was easy. And he didn't even need to talk about the stack. Heck, he didn't even need to talk about lvalues and rvalues. Kudos, PeterB.

I objected to your stack model on two grounds:

1. It contained unnecessary details (the stack) that didn't seem helpful
2. It was wrong

While (2) is true, I was really primarily objecting to (1). You really don't need a bunch of extraneous stuff to explain parameter passing.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by kennedye:
Slightly OT, but do modern C/C++ compilers actually still honor the register keyword, or is it basically C's equivalent of the human appendix?
By "honor", do you mean "do anything at all", since register was always just advice to the compiler?

I don't know for sure and I don't have time to tinker today. I imagine that there are some C compilers that ignore register and perform their own register allocation (I mean, come on, does the compiler need a hint that a variable will be "frequently used"?); and there are some that use register variables as a heuristic to guide the register allocator.

As far as I know, they all still enforce the syntactic prohibition against taking the address of a register variable.
 
Slightly OT, but do modern C/C++ compilers actually still honor the register keyword, or is it basically C's equivalent of the human appendix?

MSDEV *may* not honour the request, that is it will decide whether to or not.
GCC does always, and allows you to specify which register.
As for Turbo C (if anyone besides me still uses it), it does also.
 
Originally posted by kennedye:
Slightly OT, but do modern C/C++ compilers actually still honor the register keyword, or is it basically C's equivalent of the human appendix?
AFAIK, it never represented anything more than a suggestion -- one that the compiler was free to ignore, for whatever reason (other variables are better off kept in registers, the variable won't fit into a register, there aren't enough registers, it's a debug build and so everything is effectively <tt>volatile</tt> for ease of seeing what's going on, etc.).

<hr />

As far as I know, they all still enforce the syntactic prohibition against taking the address of a register variable.
g++ 2.95.x and MSOC 13 both permit it, I didn't bother testing anything else.

In any case, taking the address of such a variable is explicitly permitted in C++:
7.1.1.1: A <tt>register</tt> specifier has the same semantics as an <tt>auto</tt> specifier together with a hint to the implementation that the object so declared will be heavily used. [Note: the hint can be ignored and in most implementations
it will be ignored if the address of the object is taken. '”end note]

I don't know what C has to say about the matter.

<hr />

Not in Compaq C it doesn't
Doesn't what?

Pass-by-value? It most certainly does. Always.
 

gaffa

Well-known member
6,210
I agree that my explanation was too implementation oriented. I was following on from the original reply. That said, I don't see how this was improved by putting forward an equally implementation oriented reply (registers).
I don't understand the obsession with 'pass-by-value'. As opposed to pass by what?
I find it much easier to think of a variable being passed by immediate value, by reference, or by descriptor.

Cheers

Gary.
 

newton_meter

Ars Scholae Palatinae
1,424
Level_7:
GCC does always, and allows you to specify which register.
Always? Au contraire. Something about a fixed number of registers. Check it out:

Code:
#include <stdio.h>

int foo(void) {
    register int i0 = getchar();
    register int i1 = getchar();
    register int i2 = getchar();
    register int i3 = getchar();
    register int i4 = getchar();
    register int i5 = getchar();
    register int i6 = getchar();
    register int i7 = getchar();
    register int i8 = getchar();
    register int i9 = getchar();

    return i0 + i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + i9;
}
Only three of those guys (the i's) manage to not get spilled to the stack (OK, I cheated, I compiled it with gcc for i686, but you get the idea).

PeterB:
In any case, taking the address of such a variable is explicitly permitted in C++
Suprising. I never even considered trying it.
 
By newton_meter

Always? Au contraire. Something about a fixed number of registers. Check it out:

Actually, that's not what I meant. Check it out:

Code:
#include <stdio.h>
int main(void)
{
	register int* reg1 asm("a5");
	int x = 5;
	*((unsigned int*)reg1) = x;
	printf("The value of reg1 is %d", *reg1);
}

I compiled using gcc for 68K and ran it on my Coldfire sitting beside me. You should be able to use all the registers this way. You should also be able to compile on an Intel machine using AH, AX etc. However, I do think there are certain registers that are safer to use than others.
 

newton_meter

Ars Scholae Palatinae
1,424
kennedye:
Slightly OT, but do modern C/C++ compilers actually still honor the register keyword...?
Level_7:
GCC does always, and allows you to specify which register.
newton_meter:
Always? Au contraire. Something about a fixed number of registers.
Level_7:
Actually, that's not what I meant.
Do you understand the force of the word "always"? It means every single time. Exhibiting a single counterexample suffices to disprove your claim.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by glenthas:
I'm not very familiar with C so I may be wrong, but doesn't register simply specify that the variable should initially be stored in a register? Does it make any claims that a variable will not subsequently be pushed onto the stack?

What use would that be?

"register" is silly. It tells the compiler "try your hardest to put this variable in a register, if you can". Which is exactly what it does with every variable. The compiler is free to ignore you, anyway.

"register" is a hint that the variable is "frequently used". If your compiler can't figure that out on its own, it's time to get a new compiler. "register" also prohibits (in C) taking the address of the variable. Some people mistakenly believe that this frees up some other optimizations. But it doesn't enable anything that a compiler that simply looked ahead and saw that you didn't take the address of the variable anyway couldn't do. If your compiler isn't considering the entire scope of a variable when optimizing storage for that variable, it's also time to get a new compiler. Besides, if your compiler is this stupid, it probably just ignores "register" anyway.

The really funny thing is that you can get screwed on register variables too. Put a couple things that you think are important in registers, and voila! big slowdown. Why? Because, you putz, you just took away two registers that the compiler could use for something that actually was important.

In short: you never win, you could sometimes (though it's rare) lose. The moral is to not try to out-optimize your compiler at any level below that of the algorithm.

kg m²/s²
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by Level_7:
What's your point?
That your statement: "GCC does [honor the C register keyword] always, and allows you to specify which register" is demonstrably false. It does not, and I exhibited the proof.

Before you get too wedded to the idea that you can tell gcc exactly where to stick its variables, tell me how many general purpose registers you've got. Then, I'll tell you exactly how many variables you need to ensure that one value is not in a register its entire lifetime. It's called the pigeon hole principle.

Or, tell me how many bits each register is, and I'll construct a struct that's so fuckin' big it won't possibly fit in all your registers put together.

I think you're going to have to concede this one.
 

stickboy

Ars Tribunus Angusticlavius
6,218
Subscriptor
Originally posted by gaffa:
I don't see how this was improved by putting forward an equally implementation oriented reply (registers).
Did you read PeterB's explanation? It was a general, simple explanation; nowhere in it did it mention registers or a stack.

I don't understand the obsession with 'pass-by-value'.
The obsession is that in ANSI C, everything is passed by immediate value. Period. Maybe your funky Compaq C compiler doesn't (thus far you have shown no proof), but if it doesn't, I don't think it's ANSI-compliant, and if it's not ANSI-compliant, I don't know why it even got brought up.
 
Originally posted by pholus:
So, can anyone now elaborate on the "pass by reference" that was offered by petrov? Thanks in advance.
Pass-by-reference is a bit harder to explain in general terms, I think.

With pass-by-value, the function has its own set of variables (corresponding to the ones it's passed), and they get filled in by the passed variables.

With pass-by-reference, the function doesn't have its own variables. Instead, it says "I'm going to use the variables that you give me". The names used inside the function refer directly to the variables passed (they become synonyms).

Maybe ASCII art will help.

Code:
pass by value:

function foo(integer i, integer j)
calling:
foo(a, b);

==>
            -------------
            |     |     |
            |  a  |  b  |
caller      |  |  |  |  |
---------------|-----|---  each box represents a variable
callee      | \|/ | \|/ |  foo has its own set of boxes,
(foo)       |  i  |  j  |  and they get filled by the values
            |     |     |  passed to it.
            -------------
pass by reference:

function bar(integer reference i, integer reference r)
calling:
bar(a, b);

==>

            -------------
            |     |     |
            |  a  |  b  |
caller      | /|\ | /|\ |
---------------|-----|---  bar has no boxes of its own, it just 
callee         |     |     has placeholders.  When the bar is 
(bar)          i     j     called, those placeholders are set to 
                           refer to the boxes passed to it.
                           i and j become synonyms for a and b
                           (respectively), and any change to i 
                           j is reflected in a change to a or b.


Maybe it won't. I'm trying to avoid discussing how pass-by-reference achieves this goal.
 
Originally posted by gaffa:
C passes everything by value, by default. If you prefix an argument with a '&' then the address of the value (by refernece) is passed not the value.
The value of <tt>&variable</tt> is the address of <tt>variable</tt>, and that value is passed by value, not reference.

It doesn't pass things by value by default. It passes things by value because that's all it knows how to do.
 
Originally posted by pholus:
wow! ASCII art... talk about going beyond the call of duty :)
Seriously, thanks! I'm afraid my question now seems to be more on the "how" side of things. I'm having a tough time imagining how the fct can take anything but a value of the variable's address for "referencing" the variable.
Normally, it's implicitly pass-pointer-by-value. However, I imagine that for things like inlined pass-by-reference functions (where calling rules do not apply), a value might be kept in a register across the non-existant function call and back. This is why I didn't much want to say "it uses a pointer", because I'm sure there are situations where it doesn't have to.

Edit: Yes, I've checked; how pass-by-reference works is dependent on optimization and other issues.
 

gaffa

Well-known member
6,210
The value of &variable is the address of variable, and that value is passed by value, not reference.

It doesn't pass things by value by default. It passes things by value because that's all it knows how to do.

I know exactly what you saying. I just think that this may mislead a novice. C always passes arguments by value, but that value may not be the value of the variable that you passed. The value may be the address of the variable that contains the value.

I think it's much easier to say that arguments are passed either by immediate value (value of variable), by reference (value is address of variable), or by descriptor (value is address of a descriptor of variable).

Maybe it's just how I was dragged up.

Cheers

Gaffa.
 
Originally posted by gaffa:
I know exactly what you saying. I just think that this may mislead a novice. C always passes arguments by value, but that value may not be the value of the variable that you passed.
Yes, it is. Always. If you pass an integer, it'll get an integer. If you pass the address of an integer, it'll get the address of an integer. If you pass an array (including a C-string), it'll get the address of the first element of that array. It will always get the value that you pass.

The problem is that people don't know what the value of an expression is. You ask them, "what's the value of <tt>"Hello World!"</tt>?" and they'll say that it's "Hello World!". It isn't. This is why they then think that some magic goes on when they pass a string/array to a function. I think that rather than making out that the language has some magic, one is better off correcting the mistaken impression of what the value of a string/array/function actually us.

The value may be the address of the variable that contains the value.
No, it may not. If you have an <tt>int a</tt> and you pass <tt>&a</tt> then the variable you are passing is <tt>&a</tt> and the value you are passing is not <tt>a</tt>, it is the address of <tt>a</tt>.

The value isn't necessarily "what's contained". This apparent expectation that it is seems to cause more problems than it solves.

I think it's much easier to say that arguments are passed either by immediate value (value of variable), by reference (value is address of variable), or by descriptor (value is address of a descriptor of variable).
I don't think that it is. I think that thinking like that has led to Java programmers, for instance, thinking that their language has pass-by-reference, when it doesn't (it has only pass-by-value).

I think it is important for C and C++ programmers to understand what the value of an expression is, and I don't think that muddying the issue by saying such things as "C does pass-by-reference" is helpful. If it had pass-by-reference, you wouldn't need pass addresses to <tt>scanf()</tt>.
 
Status
Not open for further replies.