This is a very quick question.
Why am I allowed to do this:
char* sentence[2] ={"blahblah","trololo"};
int main() {
printf("%s",sentence[0]);
printf("%s",sentence[1]);
return 0;
}
but not this?:
char* sentence[2];
sentence[0] = "blahblah";
sentence[1] = "trololo";
int main() {
printf("%s",sentence[0]);
printf("%s",sentence[1]);
return 0;
}
You're not allowed to do the second part, because the assignment is outside of a function. When you move the assignment into main() (or another function), it will be valid
char* sentence[2];
int main() {
sentence[0] = "blahblah";
sentence[1] = "trololo";
printf("%s",sentence[0]);
printf("%s",sentence[1]);
return 0;
}
Why am I allowed to do this:
char* sentence[2] ={"blahblah","trololo"};
Initialization is allowed for global variables.
but not this?:
The statements
sentence[0] = "blahblah";
sentence[1] = "trololo";
makes no sense outside a function ( main() ). Move them inside the function and it will work.
Sorry i didnt read in a correct way the question and i didnt see the function main()
the code works every time inside the functions. the functions have to be called!
main is called by the system. so this code is not attainable.
you can put out from the functions just global variable (example costant) or struct.
Related
I am writing a code in C. It is in an environment with precoded functions, so I can't explain it completely. I wanted to iterate over a variable but this wasn't working. I eventually figured out this was because the variable was not defined globally but in a function, and was being redefined every time the function was called.
Now, at the top of my code, globally, I want to write the following code.
int killing_time = 20000;
int killing_period;
killing_period = killing_time;
The compiler gives me the following errors:
data definition has no type or storage class
Don't I clearly define it to be an integer?
initializer element is not constant
If I define killing_time as const int killing_time = 20000 it still gives the same error:
type defaults to ‘int’ in declaration of ‘killing_period'
I could of course define killing_period to be 20000 and just start iterating over that, but I want to know what is going on.
I hope we can figure this out together.
killing_period = killing_time; is not a valid statement in the global scope.
You can use assignment on declaration, but assigned variable (initializer element) must be constant:
const int killing_time = 20000;
int killing_period = killing_time;
Anyway, you shouldn't do it like that.
There's more than one way to do this, one of them is to pass the address of your iterator to the function where you use it, that way the changes made in the scope of the function are permanent:
void f1(int* i){
(*i)++; //will increment i
}
void f2(int* i){
(*i)++; //will increment i
}
int main ()
{
int i = 0;
f1(&i); //pass the address of i
f2(&i); //pass the address of i
printf("%d", i); // i = 2
return 0;
}
killing_period = killing_time; is executable code and you simply can't have executable code outside functions.
Nor can you do this:
int killing_time = 20000;
int killing_period = killing_time; // wrong
Because these are file scope variables and therefore have static storage duration. And variables with static storage duration can only be initialized by what C calls a constant expression. 20000 above is an integer constant expression, but killing_time isn't.
The simple fix is to do something like this instead:
#define KILLING_TIME 20000
...
int killing_time = KILLING_TIME;
int killing_period = KILLING_TIME;
killing_period = killing_time; is your problem. It is an executable statement and not allowed in global space... it must be within a function.
Still not sure what you are after, but would the following help?
int killing_time = 20000;
int killing_period = -1; // negative if not yet set
int your_function(void)
{
if ( killing_period < 0 ) {
/* one-time initialization on the first call */
killing_period = killing_time;
}
return killing_period;
}
If you need multiple functions setting killing_period it may be be best to burry that in a separate function dedicated to the test and set, or perhaps a macro.
I have just written a sample program to understand the working of functions in C. I declared a function in C and call it during my programs execution. However my compiler gives me a warning saying unused function. My code looks like this :
#include <stdlib.h>
#include <stdio.h>
int test_function(x);
int main(){
int x;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value;
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
int test_function(x)
{
if (x==0)
{
printf("the letters are the same");
}
return value;
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
The program seems to execute fine but I get a warning in the fourth line where I declared the function in the start of the program. The warning is :
Multiple markers at this line
- parameter names (without types) in function declaration [enabled by
default]
- Unused declaration of function 'test_function'
I think the way I am calling my function is not right. Could somebody please help me. Thnak you in advance.
Disclaimer: nested functions are non-standard C and I only know (of) the GNU extension for this. As such anything I claim here may well be untrue in another implementation. My recommendation is that you just don't use them at all.
Your nested test_function is shadowing the global declaration. So the test_function you declared above main is never called, because the call inside main refers to the nested function. Hence, you get a warning.
You should declare int test_function outside of main
for example.
int test_function(int x)
and then call the function in main.
value = test_function(x)
This is what your code should look like:
#include <stdlib.h>
#include <stdio.h>
int test_function(x)
{
int value = 0;
if (x==0)
{
printf("the letters are the same");
}
return value;
}
int main(){
int x = 0;
char letter[] ={"HAAA"};
char cmpre[] = {"AHD"};
int value = 0; // unused
for(int i=0; i<4;i++)
{
if(letter[i] == cmpre[i])
{
x=0;
}
}
printf("To check if the letters are the same go to the function");
test_function(x);
return 0;
}
Note that if you dont need a return value you could make the function void.
And initialize your variables. You may search hours to find such a error
I know that If a function has no argument & only return type (say int), then I can change my int variable by assigning the function to my variable as below,
main()
{
int var_name;
var_name = func();
printf("My variable value is updated as : %d", a);
}
func()
{ return 100; }
Also I know that If I have my function's return type as void, with no arguments, then I can only print the value inside the function itself and cannot return anything in turn.
But, my doubt is, is there anything else that I can do to update my var_name by calling a function with no arguments & no return type ?
ie., void func(void); by using something like pointer concepts ??
I could not able to find the exact answer for the same by my searches among so many websites.. I will be very grateful if someone can help me out finding whether I can do it by this way or not,.
Thanks,.
It is possible to modify a local variable in main, from a function with no arguments and no return value, if there's a global pointer to it:
#include <stdio.h>
int *p;
void func() {
*p = 6;
}
int main() {
int a = 5;
p = &a;
func();
printf("a = %d\n", a); // prints: a = 6
return 0;
}
There's no good way to do that. If you want the function to modify a local variable, you should probably change the function so it either returns a value that you can assign to the variable, or takes the variable's address as an argument.
But if you don't mind writing some ugly code, you can define a global (file-scope) pointer variable, assign the local variable's address to the global pointer, and then use that to modify the variable inside the function.
An example:
#include <stdio.h>
int *global_pointer;
void func(void) {
*global_pointer = 42;
}
int main(void) {
int local_variable = 0;
global_pointer = &local_variable;
func();
printf("local_variable = %d\n", local_variable);
}
It's very easy to shoot yourself in the foot his way. For example, if you refer to the pointer after the calling function has terminated (and the local variable no longer exists), you'll have undefined behavior.
This technique can actually be useful if you need to make a quick temporary change in a body of code in which you can't make major interface changes. Just don't do it in code that will be maintained by anyone else -- and wash your hands afterward.
You can have global variable
int var_name;
void func();
int main()
{
func();
printf("%d\n",var_name);
}
void func()
{
var_name = 20;
}
But if your variable is local to main() then this can't be done.
There are two ways to modify the value of var_name.
Make changes in the calling function and return the value.( which you have already shown)
Pass the address of the var_name to the function and have pointer as arguement in the func(int *p) and modify the value inside the func()
Thats it!! No other way this can be done.
I have the following code below in a function.
char * stringFiveds = strtok(stringFive[3], "ds");
When I compile i get the warning unused variable.
I don't plan on using srtingFiveds in this function. I want to use it in main(). I have two parts to this question.
How to solve this warning if I don't want to use the stringFiveds in this function.
How do I make it accessible in other functions so i can use it in other function i will create.
I'm new to this, can you please be as detailed as possible.
If you don't want to use stringFiveds in the function, you can delete that variable declaration because you don't need it.
If you want to make it accessible to other functions, you can declare it as a global variable, or pass it as an argument to your other functions.
So instead of
char * stringFiveds = strtok(stringFive[3], "ds");
you can have just
strtok(stringFive[3], "ds");
If you want to declare stringFiveds as a global variable, just declare it outside of a function:
#include <stdio.h>
char * stringFiveds; // declare outside of function
void foo() {
// you can access stringFiveds here
}
int main() {
// you can also access stringFiveds here
}
If you want to pass stringFiveds as a function argument:
#include <stdio.h>
// declare outside of function
void foo(char * stringFiveds) {
}
int main() {
char * stringFiveds;
foo(stringFiveds);
}
If you do not plan to use a variable in a function, do not make a variable. If you make a variable simply for the side effects of calling a function, you could drop the assignment: C lets you call a function that returns a value as if it were a "procedure" - i.e. a void function.
Another alternative is declaring the variable in the global scope. If you choose this route, consider making the variable static to keep it within the scope of its translation unit. You could also make the variable global, but that is usually not a good option, because it exposes your data beyond the bounds where it is useful.
If you plan to pass it to another function, that would count as "using the variable", resolving the "unused variable" warning.
Note: in case you are curious on how to silence this warning anyway, a common trick is to cast your variable to void.
Well, you could do the gross thing and make it a global variable (i.e. declare is outside of your function).
But that really isn't a great solution. That breaks data encapsulation by giving everything in your .c file access to that variable, whether they need to know about it or not.
A better solution would be to pass in to your functions as a parameter where you need it.
For example:
function foo(char* stringFiveDs) { // use stringFiveDs here }
Or, you could pass in stringFive and declare stringFiveDs in the functions that you need it. So something like:
function bar(const char* stringFive) {
char* stringFiveDs = strtok(stringFive[3], "ds");
...
}
sample code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **func(const char *str, const char *delim){
char *strwk = strdup(str);
char **strs = malloc(sizeof(char*));
int count = 0;
char *p;
for(p=strtok(strwk, delim); p != NULL ; p=strtok(NULL, delim)){
strs[count++] = strdup(p);//cutting string copy into
strs = realloc(strs, (count+1)*sizeof(char*));//+1 : Also, reserved for NULL
}
strs[count] = NULL;//end mark
free(strwk);
return strs;
}
void func_d(char **ss){
char **sp = ss;
while(*sp)
free(*sp++);
free(ss);
}
int main(void){
char *stringFive[5] = {
"", "16X16", "1,2,3", "123d45s678", "last,,end"
};
char **stringFiveds = func(stringFive[3], "ds");
int i;
for(i=0; stringFiveds[i] != NULL; ++i)
printf("%s\n", stringFiveds[i]);
func_d(stringFiveds);
return 0;
}
Can someone explain why the value of the variable test isn't changed when I run the short code snippet below?
#include <stdio.h>
int f1(char * foo) {
*foo = 'a';
return 0;
}
void main(void) {
char test = 'n';
printf("f1(&test)=%d. test's new value? : %c", f1(&test), test);
}
I know I'm probably missing something really simple. I just don't understand why test isn't changed in f1() because I'm passing it's address in, right? Why does it matter that the actual function call happens in the list of arguments to printf() ?
If I take the call to f1() out of the printf argument list like so:
#include <stdio.h>
int f1(char * foo) {
*foo = 'a';
return 0;
}
void main(void) {
char test='n';
int i;
i = f1(&test);
printf("f1(&test)=%d. test's new value? : %c", i, test);
}
things work as expected.
thanks in advance.
The order in which the arguments to a function call are evaluated is unspecified. Put another way, you can't tell for sure when f1(&test) will be evaluated.
So in your example, perhaps f1(&test) is evaluated after test: slightly counter-intuitively, you don't get to see the side effects of that invocation. But if you print test again after the call, you will indeed see them.
Bottom line, just be careful with function that have side-effects and you should be set.
There is no set order in which function parameters are evaluated. You're banking on the idea that the arguments are evaluated left to right, which can't be assumed.
Just change where you make your function call
#include <stdio.h>
int f1 (char* foo) {
*foo='a';
return 0;
}
int main(void)
{
char test='n';
f1(&test);
printf("test=%c\n", test);
return 0;
}