C言語での参照渡しとは何ですか?
Cプログラミング言語での参照渡しは、引数として送信されるアドレスです。
アルゴリズム
C言語での値渡しの動作を説明するアルゴリズムを以下に示します。
START Step 1: Declare a function with pointer variables that to be called. Step 2: Declare variables a,b. Step 3: Enter two variables a,b at runtime. Step 4: Calling function with pass by reference. jump to step 6 Step 5: Print the result values a,b. Step 6: Called function swap having address as arguments. i. Declare temp variable ii. Temp=*a iii. *a=*b iv. *b=temp STOP
サンプルプログラム
以下は、参照渡しを使用して2つの数値を交換するCプログラムです-
#include<stdio.h>
void main(){
void swap(int *,int *);
int a,b;
printf("enter 2 numbers");
scanf("%d%d",&a,&b);
printf("Before swapping a=%d b=%d",a,b);
swap(&a, &b);
printf("after swapping a=%d, b=%d",a,b);
}
void swap(int *a,int *b){
int t;
t=*a;
*a=*b; // *a = (*a + *b) – (*b = * a);
*b=t;
} 出力
上記のプログラムを実行すると、次の結果が得られます-
enter 2 numbers 10 20 Before swapping a=10 b=20 After swapping a=20 b=10
別の例を見て、参照渡しについて詳しく見てみましょう。
例
以下は、参照による呼び出しまたは参照による受け渡しを使用して、呼び出しごとに値を5ずつインクリメントするCプログラムです。
#include <stdio.h>
void inc(int *num){
//increment is done
//on the address where value of num is stored.
*num = *num+5;
// return(*num);
}
int main(){
int a=20,b=30,c=40;
// passing the address of variable a,b,c
inc(&a);
inc(&b);
inc(&c);
printf("Value of a is: %d\n", a);
printf("Value of b is: %d\n", b);
printf("Value of c is: %d\n", c);
return 0;
} 出力
上記のプログラムを実行すると、次の結果が得られます-
Value of a is: 25 Value of b is: 35 Value of c is: 45
-
C言語の例の定数は何ですか?
定数は変数とも呼ばれ、一度定義されると、プログラムの実行中に値が変更されることはありません。したがって、固定値を参照する定数として変数を宣言できます。リテラルとも呼ばれます。定数を定義するには、Constキーワードを使用する必要があります。 構文 Cプログラミング言語で使用される定数の構文を以下に示します- const type VariableName; (or) const type *VariableName; さまざまな種類の定数 Cプログラミング言語で使用されるさまざまな種類の定数は次のとおりです- 整数定数 −例:1,0,34,4567 浮動小数点定数 −例:0.
-
C言語でのシフト演算とは何ですか?
問題 C言語を使用して、数値の左シフト、右シフト、および補数を表示する簡単なプログラムは何ですか? 解決策 左シフト 変数の値が1回左シフトされると、その値は2倍になります。 たとえば、a =10、次にa <<1 =20 右シフト 変数の値を1回右シフトすると、その値は元の値の半分になります。 1 =5 例 以下はシフト操作のCプログラムです- #include<stdio.h> main (){ int a=9; printf("Rightshift of a = %d\n",a&