2

Say I have a function in C defined as :

bool check ( int x, int y);

Now if I call it using check(4);

What will be the value of y that is taken?

9
  • 2
    will it be even compiled successfully? Commented Jul 27, 2012 at 19:47
  • It would read the second value of the stack and store it in y. Undefined behavior. Commented Jul 27, 2012 at 19:53
  • 1
    @jsn: Nothing in the language definition suggests that it would do anything with the stack; the standard doesn't even mention the word. Commented Jul 27, 2012 at 20:03
  • 1
    Why do you suppose that the 4 matches the first parameter? It could be that you "forgot" the first and not the second parameter. Commented Jul 27, 2012 at 20:51
  • 1
    @jsn: My point is that the behavior you described is not guaranteed. Even on systems with a contiguous stack, the behavior could vary depending on the order in which parameter are passed; I could easily imagine x being set to garbage and y to 4. (If you had written "could" rather than "should", I wouldn't have responded.) IMHO it's important to know what "undefined behavior" really means. Commented Jul 28, 2012 at 0:21

1 Answer 1

7

Code like this can possibly compile only if the function is either undeclared (C89/90) or declared without a prototype (C89/90 and C99).

In any case the behavior will be undefined. If the number and/or type of promoted arguments used in the call do not match those used in the function definition, the behavior is undefined.

6.5.2.2 Function calls

6 [...] If the number of arguments does not equal the number of parameters, the behavior is undefined [...] If the function is defined with a type that does not include a prototype, and the types of the arguments after promotion are not compatible with those of the parameters after promotion, the behavior is undefined

Sign up to request clarification or add additional context in comments.

2 Comments

A compiler is still permitted to reject the program; that's one possible consequence of undefined behavior.
@dasblinkenlight: Right, declarations are mandatory (as of C99), but prototypes are still optional, even as of C11. (Which is a pity, IMHO; non-prototype function declarations have been "obsolescent" since 1989.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.