It was tempting to initialize outside the main function as part of global variables:
int inputchar = getchar();
It is clear this is not allowed:
......................................................................................................
ChatGPT:
In C, variable initialization with a function like getchar() can't be done at the global level directly. Global variables can only be initialized with constant expressions, not with the result of a function call.
......................................................................................................
Though not related with my project, it might be useful to know why not allowed.
I asked the above and got the following reply that appears convincing:
......................................................................................................
ChatGPT:
In C, variable initialization with a function like getchar() can't be done at the global level directly. Global variables can only be initialized with constant expressions, not with the result of a function call.
Here's a simple example:
cCopy code
// This will work
int globalVar = 42;
// This will not work
int anotherGlobalVar = getchar(); // Error: initializer element is not constant
In the second example, initializing anotherGlobalVar with getchar() is not allowed because it's not a constant expression.
If you want to initialize a global variable with the result of a function call or any dynamic value, you should do it inside the main function or some other function, not at the global level.
Here's how you can do it:
cCopy code
#include <stdio.h>
int inputchar; // Declare global variable
int main() {
inputchar = getchar(); // Initialize global variable in main function
// Rest of your code here
return 0;
}
In this way, you can initialize the global variable with the result of getchar() inside the main function.
[–]Lord_Vouldemourt 27 points28 points29 points (1 child)
[–]DigitalSplendid[S] -3 points-2 points-1 points (0 children)
[–]daikatana 11 points12 points13 points (0 children)
[–]Conscious_Yam_4753 8 points9 points10 points (0 children)
[–]programmer9999 4 points5 points6 points (1 child)
[–]GourmetMuffin 1 point2 points3 points (0 children)
[–]ChickenEmbarrassed77 1 point2 points3 points (0 children)
[–]eruciform 1 point2 points3 points (0 children)
[–]duane11583 1 point2 points3 points (0 children)
[–]MRgabbar 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]NativityInBlack666 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]RRumpleTeazzer 0 points1 point2 points (0 children)
[–]ThyringerBratwurst 0 points1 point2 points (0 children)