c programming practice examples

Thread Starter

Gajyamadake

Joined Oct 9, 2019
145
This is not the way to learn C keywords.
Read what the keyword does. Look at examples and explanations of what it does.
And if you don't see a difference, don't use it until you fully understand its purpose.
I have written the few codes First code is working as I suppose to do but getting errors in other codes
Example #1
C:
#include<stdio.h>

void delay (void)
{
    unsigned int i;
    for (i = 0; i < 6; i++)
    {
        printf("Loop  :  %d \n", i);
    }
         
}

int main (void)
{
  delay();

   return 0;
}
Loop : 0
Loop : 1
Loop : 2
Loop : 3
Loop : 4
Loop : 5


Example #2 Error What does it means invalid use of void expression ?
C:
#include<stdio.h>

void delay (void)
{
    unsigned int i;
    for (i = 0; i < 6; i++)
    {
        printf("Loop  :  %d \n", i);
    }
         
}

int main (void)
{
  delay();

  printf("Loop  :  %d \n", delay());   // Error invalid use of void expression//

   return 0;
}
Example #3
error: void value not ignored as it ought to be
int count = delay (); // declaring variable to store function value

C:
#include<stdio.h>

void delay (void)
{
    unsigned int i;
    for (i = 0; i < 6; i++)
    {
        printf("Loop  :  %d \n", i);
    }
         
}

int main (void)
{
   int count = delay (); // declearing variable to store function value

   printf("Loop  :  %d \n", count);  

   return 0;
}
I would appreciate your any help
 

MrChips

Joined Oct 2, 2009
19,413
Example #2 - Your delay( ) in the printf statement has no value.

Example #3 - int count is a variable definition. You cannot assign delay( ) to this variable.
 

Ian Rogers

Joined Dec 12, 2012
666
Volatile.... Compilers come with levels of optimisation.. If you have a variable that is updated via an interrupt ( outside of main ) but you use it inside the main, the compiler will not recognise the variable ( even though used in the interrupt ) has a use.. SO!! specifying volatile will allow the compiler to keep the variable..

C:
int sum;

void interrupt isr(void){
   sum++;
}

void main(void){
   if (sum == 10) do_something();
}
without the volatile specifier.. The optimised compiler will ignore sum as it doesn't appear to do anything..
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
145
Example #2 - Your delay( ) in the printf statement has no value.

Example #3 - int count is a variable definition. You cannot assign delay( ) to this variable.
When delay () function execute It doesn't pass any value and it doesn't return any value. This is reason I can't store value in variable in main

Example #4 : function return integer and doesn't pass anything

C:
#include<stdio.h>

int addition(void);

int main(void)
{
   int add = addition();

   printf(" addition = %d ", add);

   return 0;
}

int addition (void)
{
     int result;
 
     int x = 2; int y = 3;
     result = x + y ;
 
    return result;
}
function int addition(void); return integer value

addition = 5
 

MrSoftware

Joined Oct 29, 2013
1,573
Volatile should be used on any variable that may be modified by code that is not nearby in the same thread. That's a bit vague, but basically using the volatile keyword tells the compiler that every time the variable is read, it should first be fetched from main memory. For example, if you have the following (pseudo code):

Code:
volatile int gStopLoop;

void myInterruptRoutine()
{
    gStopLoop = true;
}

main()
{
    gStopLoop = false;
  
    // Insert some code that sets up myInterruptRoutine() which will be
    // called at random when triggered by an external input

    while(!gStopLoop)
    {
        printf("Still looping");
    }
}
Here without the volatile qualifier, a compiler might optimize the code for speed, and since gStopLoop does not appear to be modified anywhere near the while(), the compiler will read the value for gStopLoop from main memory on the first loop, then just continue to use the value stored in a CPU register or cache after that. Getting values from main memory is slower, it takes multiple clock cycles to get data from main memory where as register values are available immediately, so this is a speed optimization. When the interrupt routine is called, the value in main memory will be modified, but then the processor will pop the stack and go right back to where it left off in the loop as if nothing happened, and continue using the cached value for gStopLoop. By using the volatile keyword, the compiler will now go out and read the value for gStopLoop from main memory on every loop. This is slower, but eliminates the error of using a cached value when the value in main memory has changed.

To understand this type of thing, do a little reading on interrupt routines, CPU registers, cache and main memory. There are other conditions where volatile is useful, but this is the easiest to explain that I can think of.
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
145
Change the definition of delay( ) to
I can pass the single integer to function. I am struggling to pass array to function I have no idea How do we pass array to function ?

Example #6 Pass array to function

C:
#include <stdio.h>

void function( int value[5])
{
    int i;
  
    for( i = 0; i < 5; i++)
      
        {
            value[i] = value[i] + 10;
          
            printf ("value : %d", value[i])
        }
}

int main()
{
   int array [];  // array declration
  
   array = function () // call function
  
    return 0;
}
 
Last edited:

MrChips

Joined Oct 2, 2009
19,413
You cannot pass the contents of the array. You need to pass the address of the array.
You need to learn about memory addressing and pointers.
This is stepping into more advanced areas of programming. Perhaps you should wait until you have done some exercises using characters and strings.
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
145
You cannot pass the contents of the array. You need to pass the address of the array.
Are you sure? can you tell me reason why we can't pass the array

You need to learn about memory addressing and pointers.
pointer is a variable that can store the address of another variable
Example #6 : I hope It's clear explanation about memory addressing and pointers
C:
#include <stdio.h>

int main()
{
    int i;

    int array[5] = {10, 12, 31, 40, 25};  // assign integer value to array

    int *pointer = array;     // same as int*p = &a[0]

    for (i = 0; i < 5; i++)   // Loop to print array element and address of element
    {
        printf("\n Value :%d ", *pointer); // we can access variable indirectly using pointers
     
        printf("\n %p ", pointer);  // Print the value of pointer that is address of array element
     
        pointer++;  // it's different then the normal increment , size of int data type is 4 bytes it will increment byte
    }
 
    return 0;
}
Value :10
0061FF14
Value :12
0061FF18
Value :31
0061FF1C
Value :40
0061FF20
Value :25
0061FF24
 
Last edited:

MrChips

Joined Oct 2, 2009
19,413
What you have demonstrated is passing one element of the array at a time by passing value[i].
In your pointer example using pointers, you are passing one address, i.e. the address of one element.

As I stated, you cannot pass all the contents of an array.
Imaging that you have an array that is 1000 elements long. How can you pass that many data?
What you can pass is the address of one element in the array or you can pass the address of the first element and then assume that all subsequent elements are stored sequentially, packed as n-bytes per element.
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
145
Imaging that you have an array that is 1000 elements long. How can you pass that many data?
What you can pass is the address of one element in the array or you can pass the address of the first element and then assume that all subsequent elements are stored sequentially, packed as n-bytes per element.
Example 7 : Passing the address of one variable to function

C:
#include<stdio.h>

void function(int *p)
{
   *p=10;
}

int main()
{
      int a = 0;
    
      function(&a);  // passing address of a
    
      printf("a = %d", a); // getting value by the addres
    
      return 0;
}
a = 10

Example 8: Passing array to function. I am struggling to pass array to function
C:
#include<stdio.h>

void function(int *pointer)
{

}

int main()
{
      int array[] = {11, 12, 31, 41, 15};
    
      function(&array[]);  // passing address of array
    
      printf("a = %d", array[0]);
    
      return 0;

}
Example 9: This code found on the google (Edited to make simple )

Code:
#include <stdio.h>

void fun(int *pointer)
{
   int i;
   for ( i = 0; i < 5; i++)
     printf("%d  ", pointer[i]);
}
 
int main()
{
   int array[] = {1, 2, 3, 4, 5}; 

   fun(array);  // I don't understand this line. there is no & operator 
 
   return 0;
}
1 2 3 4 5
 
Last edited:

MrSoftware

Joined Oct 29, 2013
1,573
You can pass a copy of an array to a function, it's not recommended, but you can do it by making it part of your own data type. See the really ugly but functional example below. Generally speaking don't do this unless you have a very specific need. It's slow and if the struct is big enough you can get a stack overflow which can lead to all sorts of fun issues to chase after if the operating system doesn't crash your program.

C:
#include <stdio.h>

typedef struct
{
    int arr[5];
}mysruct;

void fun(mysruct lstruct)
{
    printf("One: \n");
    for(int i = 0; i < 5; i++)
    {
        printf("%i ", lstruct.arr[i]);
        lstruct.arr[i] = -1;
    }
    printf("\n");

    printf("Two: \n");
    for(int i = 0; i < 5; i++)
    {
        printf("%i ", lstruct.arr[i]);
    }
    printf("\n");
}

int main()
{
   mysruct it = { .arr[0] = 1, .arr[1]=2, .arr[2]=3, .arr[3]=4, .arr[4]=5 };


   fun(it);

    printf("Three: \n");
    for(int i = 0; i < 5; i++)
    {
        printf("%i ", it.arr[i]);
    }


   return 0;
}
1572882220473.png
 

MrChips

Joined Oct 2, 2009
19,413
If x is defined as an array,
then x[n] passes the contents of the nth element (starting to 0)
Passing x passes the address of x. You do not need to specify &x.
You can achieve the same thing by passing &x[0].
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
145
Passing x passes the address of x. You do not need to specify &x.
You can achieve the same thing by passing &x[0].
I hope I am not doing mistake to understand your advice
Code:
#include <stdio.h>

void fun(int *pointer)
{
   int i;
   for ( i = 0; i < 5; i++)
     printf("%d  ", pointer[i]);
}
 
int main()
{
    int a = 0;
    
   int array[] = {1, 2, 3, 4, 5};

   fun(&array[0]);  // I don't understand this line. there is no & operator
 
   return 0;
}
1 2 3 4 5
 

MrSoftware

Joined Oct 29, 2013
1,573
The key takeaway is that the name of an array is a pointer to the first element. So if you do this:

int myarray[5];

Then "myarray" is a pointer to (the address of) the first element. You can ALSO get the address of the first element using the address-of operator like this: &(myarray[0]). So "myarray" == "&(myarray[0])", it's the same exact thing.

C:
int array[5] = { 0 }; // Initialize all elements to 0
int a = array[0];  // This gives you the integer value stored in element 0
int *a = &(array[0]);  // This gives you the address of element 0
int *a = array; // This also gives you the address of element 0
 

MrChips

Joined Oct 2, 2009
19,413
This is something one needs to pay attention to because it comes up very often when creating functions.

When you are passing parameters in and out of a function, you can pass the parameter by reference or by value.

int num;
int array[5];

When you pass num in the function call you are passing the parameter by value. To pass the parameter by reference you specify &num.

array is passed by reference, i.e. by its address. Hence passing array is passing the address of array.

& is called the addressing operator
* is called the dereferencing operator
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
145
This is something one needs to pay attention to because it comes up very often when creating functions.

When you are passing parameters in and out of a function, you can pass the parameter by reference or by value.
Example : 9 Passing structure to function by value

C:
#include <stdio.h>
struct student
{
    int x;
    int y;
};

// function prototype
void display(struct student mypoint);

int main()
{
    struct student mypoint;
    mypoint.x = 1;
    mypoint.y = 2;
   
    display(mypoint);   // passing struct as an argument
   
    return 0;
}

void display(struct student mypoint)
{
  printf("\n Displaying information\n");
  printf("\n x: %d", mypoint.x);
  printf("\n y: %d", mypoint.y);
}
Displaying information

x: 1
y: 2

Example : 10 Passing structure to function by reference

Code:
#include <stdio.h>
struct student
{
    int x;
    int y;
};

// function prototype
void display(struct student *mypoint);

int main()
{
    struct student mypoint;
    mypoint.x = 1;
    mypoint.y = 2;
   
    display(&mypoint);   // passing struct as an argument
   
    return 0;
}
void display(struct student *mypoint)
{
  printf("\n Displaying information\n");
  printf("\n x: %d", mypoint->x);
  printf("\n y: %d", mypoint->y);
}
Displaying information

x: 1
y: 2

We are passing the parameter (structure) by reference or by value. Which method is more useful in coding ?
 

djsfantasi

Joined Apr 11, 2010
5,704
Yes. Both.

Both techniques are valid. Which one is more useful requires an understanding of the difference between them and of the program requirements.

I can suggest a couple of cases, but these are not all inclusive.

If the function parameters are strictly inputs, then pass by value. In this case, there or no changes to the parameters or any changes to the parameters should not be passed back.
if the parameter is a large array or structure, then copying the values may result in a memory issue.
 

MrChips

Joined Oct 2, 2009
19,413
Your two examples are the same, passing by reference.

When you pass a parameter by value, the value is passed either on the stack or in a register. The code cannot modify the variable.

Passing by reference is used when passing an array or structure. The code is able to modify the contents of the variable, array or structure since the code has the memory location of the variable.
 
Top