Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c - A constant being assigned to another constant without errors

I'm currently learning about pointers and the concept of pass-by-value, and I have this C code block:

void doSomething(int b){
    b = 6;
    printf("%d", b);
}
    
int a = 5;

int main(void){
    doSomething(a);
    printf("%d",a);
    return 0;
}

I should get the output 65 with no errors on compilation nor on execution. By tracing the code, here is how I'm seeing it:

  • Integer a is assigned the value 5.
  • Since C is strictly pass-by-value, doSomething(a) == doSomething(5).

Now prior to running the line b = 6;, I'm fairly certain that b == 5. So by running the line, the program is effectively reading:

5 = 6;

A constant (for a lack of a better term on my part) is being assigned to another constant. In Python this would have failed with a syntax error, and it makes sense to have an error. Why doesn't it raise a syntax error?

question from:https://stackoverflow.com/questions/65929555/a-constant-being-assigned-to-another-constant-without-errors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is how the C 2018 standard says function calls are executed, in 6.5.2.2 4:

In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument…

What this means is that, in the function definition with void doSomething(int b), b is defined to be a variable (technically an object) on its own, and, when the function is called with doSomething(a) or doSomething(5), the value of a or 5 is assigned to b, as if you did b = a or b = 5. It is just an assignment; it does not create any enduring connection between b and a or 5.

Inside the function, b is a variable, so of course you can execute the assignment b = 6. This simply assigns 6 to the variable b.

Here is more about how parameters are their own variables. 3.16 defines parameter as:

… object declared as part of a function declaration or definition that acquires a value on entry to the function,…

6.9.1 9 says:

Each parameter has automatic storage duration; its identifier is an lvalue…


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...