4 ms·
C code in similar spirit: $ gcc weird-0.c $ ./a.out No output from weird-0 $ gcc weird-1.c $ ./a.out foo(42) Output from weird-1. What is weird-0
by kazinator 5y ago
C code in similar spirit:
$ gcc weird-0.c
$ ./a.out
No output from weird-0
$ gcc weird-1.c
$ ./a.out
foo(42)
Output from weird-1. What is weird-0?
$ cat weird-0.c
#include <stdio.h>
void foo(int x)
{
printf("foo(%d)\n", x);
}
int x = 42;
int main(void)
{
#if __LINE__ % 2 == 0
typedef int foo;
#endif
foo(x);
return 0;
}
OK, how does weird-1 differ from weird-0? One blank line!
$ diff -u weird-0.c weird-1.c
--- weird-0.c 2022-02-16 12:09:29.565563802 -0800
+++ weird-1.c 2022-02-16 12:09:38.185718722 -0800
@@ -7,6 +7,7 @@
int x = 42;
+
int main(void)
{
#if __LINE__ % 2 == 0
Explanation:
{
#if __LINE__ % 2 == 0 // If this line number is even
typedef int foo; // foo is a typedef name for int
#endif
foo(x);
return 0;
}
If foo is a typedef name for int, then "foo(x)" is syntactically declaration. It's declaring a local variable x to be of type foo, alias for int.
If the typedef is missing, then foo(x) refers to the file-scope identifiers: the function foo and variable x. It is a call to foo passing the value 42 of x.
The preprocessor conditional could easily introduce a syntax error, but the issue in Perl is that a parsing decision (how the / token is lexically categorized) is made based on the compile-time value assigned to f. This is similar to the compile-time meaning of foo we are setting up with the presence or absence of the typedef.
- kazinator 5y agoWith a small change to the weird-0 and weird-1 programs: $ gcc -O2 -Wall -W weird-0.c weird-0.c: In function ‘main’: weird-0.c:15:7: warning: unused variable ‘x’ [-Wunused-variable] foo(x); ^ $ gcc -O2 -Wall -W weird-1.c weird-1.c: In function ‘main’: weird-1.c:16:3: error: too few arguments to function ‘foo’ foo(x); ^~~ weird-1.c:3:6: note: declared here void foo(int x, int y) ^~~ The change is in the foo function: void foo(int x, int y) { printf("foo(%d, %d)\n", x, y); } The call is now erroneous, and with the increased compiler optimization level and diagnostics, the declaration case diagnoses x being unuse